我的程序所做的是首先打印当前时间,然后用户按下回车键。然后再打印出时间并计算用户等待输入的时间。
我无法抽出时间来减去。我从stackoverflow中的另一个问题中获取了打印本地时间的代码。
#include <iostream>
#include <ctime>
using namespace std;
void main()
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ( "Current local time and date: %s", asctime (timeinfo) );
cout << "Press enter" << endl;
cin.ignore();
time_t rawtime2;
struct tm * timeinfo2;
time ( &rawtime2 );
timeinfo2 = localtime ( &rawtime2 );
printf ( "Later local time and date: %s", asctime (timeinfo2) );
printf ( "You took %s", ( asctime (timeinfo2) - asctime (timeinfo) ) ); //math won't work here
printf ( " seconds to press enter. ");
cout << endl;
}
答案 0 :(得分:4)
cout << "Elapsed time: " << rawtime2 - rawtime << " seconds" << endl;
答案 1 :(得分:4)
printf ( "You took %s", ( asctime (timeinfo2) - asctime (timeinfo) ) ); //math won't work here
没有。在这种情况下,两个char*
之间的差异没有任何意义。你真的只需要采用已经在整数秒内的rawtime
和rawtime2
,的差异。
此外,您不应在c++代码中混用printf()
和std::cout
,因为它不是惯用的,并且使代码更难阅读。因此,也许这样的事情会更好......
#include <ctime>
#include <iostream>
int main()
{
time_t rawtime;
struct tm* timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
std::cout << "Current local time and date: " << asctime(timeinfo);
std::cout << "Press enter\n";
std::cin.ignore();
time_t rawtime2;
struct tm* timeinfo2;
time(&rawtime2);
timeinfo2 = localtime(&rawtime2);
std::cout << "Later local time and date: " << asctime(timeinfo2);
time_t const timediff = rawtime2 - rawtime;
std::cout << "You took " << timediff << " seconds to press enter.\n";
}
答案 2 :(得分:0)
这是一个稍微清洁的解决方案,主要区别在于使用int main()并返回0;最后,main应该永远不会返回void,这是一个糟糕的编程习惯。
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
cout << "Current local time and date: " << asctime (timeinfo) ;
cout << "Press enter" << endl;
cin.ignore();
time_t rawtime2;
struct tm * timeinfo2;
time ( &rawtime2 );
timeinfo2 = localtime ( &rawtime2 );
cout << "Later local time and date: " << asctime (timeinfo2) << endl;
int prinAll = rawtime2 - rawtime;
cout << "You took " << prinAll << " seconds to press enter" << endl; //math won't work here
cout << endl;
return 0;
}