2013-05-30 77 views
1

我需要一個每秒鐘執行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; 
} 
+1

使用了所有的CPU,而你等待超時真的是沒辦法了。無論如何,這與定時器無關。 'std :: cout'被緩衝。 – chris

回答

1

endl導致緩衝區'flush'並寫出到標準輸出。您可以添加<< endl;cout << counter--,手動刷新使用cout.flush(); cout流,或追加<< flush;cout表達(感謝@Rob!)

欲瞭解更多信息的目的,答案this question似乎進入詳細。

2

加上<< flush你想要刷新的地方。即改變你的打印輸出:

cout << counter-- << ", " << flush;