尝试编写一个代码,其中输出应在延迟 2 秒后使用间隔计时器显示文本


#include <stdio.h>
#include <time.h>
int main()
{
    time_t now;
    struct tm timespace;
    double seconds;
    struct timespec t = { 2 /*seconds*/, 0 /*nanoseconds*/ };
    while (1) {
        time(&now);
        seconds = now;
        printf("%.f Timer Countern", seconds);
        timespace = *localtime(&now);
        nanosleep(&t, NULL);
        time(&now);
        seconds = now;
        fflush(stdout);
        printf("%.f Counter Value After two second delay.n Hellow.n", seconds);
        seconds = now;
        printf("nnn");
        timespace = *localtime(&now);
        nanosleep(&t, NULL);
        fflush(stdout);
        time(&now);
        seconds = now;
        printf("%.f Counter Value After two second delay.n Hello World 2.n", seconds);
        return 0;
    }
}

每次我编译这段代码时,它都会说:

variable `timespec t' has initializer but incomplete type

'nanosleep' undeclared (first use this function) 

如果我想要一个时间延迟,我会做这样的事情:

int t = time( NULL );
int delay = 2;
while( time(NULL) < (t + delay) );
std::cout << "...";

它相当接近两秒的时间延迟。

最新更新