我需要一個每秒鐘執行X的計時器。 我做了這個,但是直到程序終止它纔打印任何東西,我覺得很奇怪。 如果你把三個作爲計數器,它會在三秒鐘後打印所有內容,如果你選擇了三個,那麼它會打印一切。一秒計時器
如何在終止時每秒打印一次而不是全部打印?
int main()
{
using namespace std;
//Number to count down from
int counter = 10;
//When changed, a second has passed
int second = (unsigned)time(NULL);
//If not equal to each other, counter is printed
int second_timer = second;
while (counter > 0) {
second = (unsigned)time(NULL);
while (second != second_timer) {
//Do something
cout << counter-- << ", ";
//New value is assigned to match the current second
second_timer = second;
}
}
cout << "0" << endl;
return 0;
}
使用了所有的CPU,而你等待超時真的是沒辦法了。無論如何,這與定時器無關。 'std :: cout'被緩衝。 – chris