[英]How to make a timer in C?
我使用stdlib.h
標頭文件和time.h
標頭在C中使用計時器。 我陷入了一個錯誤。 如果您能幫助我,我會很高興。 我的代碼是:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main()
{
int s;
int m = 0;
while (s<=60)
{
system("clear");
printf("%d Minutes %d Seconds", m, s);
sleep(1000);
s+=1;
if (s==60)
{
m+=1;
s=0;
}
}
return 0;
}
該程序不顯示任何輸出,而是顯示空白屏幕。
由於stdout的輸出是line-buffered
,因此,如果需要更新行內的輸出(在打印\\n
之前),則需要使用fflush()
刷新緩沖區。
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main()
{
int s = 0; // init it
int m = 0;
while (s <= 60)
{
system("clear");
printf("\r"); // move cursor to position 0
printf("%d Minutes %d Seconds", m, s);
fflush(stdout); // flush the output of stdout
sleep(1); // in seconds
s += 1;
if (s==60)
{
m+=1;
s=0;
}
}
return 0;
}
sleep(1000)
將進入睡眠狀態1000秒。 您還必須將s
初始化為零,因為您正在while
循環中讀取它。 sleep
是在unistd.h中定義的,因此您也應該包括它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.