2

我的程序所做的是它首先打印当前时间,然后用户按下回车键。之后它再次打印出时间并计算用户等待按Enter键的时间。

我没时间去减法。我从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;
}
4

3 回答 3

4
cout << "Elapsed time: " << rawtime2 - rawtime << " seconds" << endl;
于 2013-04-07T03:26:07.267 回答
4

printf ( "You took %s", ( asctime (timeinfo2) - asctime (timeinfo) ) ); //math won't work here

不。在这种情况下,两个 s 之间的区别char*没有任何意义。你真的只需要取 和 的差,rawtime它们已经以秒为单位rawtime2

此外,您不应该在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";
}

笔记:

main()应该返回int,不是void

于 2013-04-07T03:38:34.073 回答
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;
}
于 2013-04-07T05:07:43.983 回答