【发布时间】:2014-07-09 16:50:53
【问题描述】:
我根据第 5 章中的内容编写了一个简单的程序,列出了 C++ Primer 第 5 版中的 5.14,据说是为了获取用户的输入时间并使程序“等待”该时间(以秒为单位)。该程序使用 while 循环执行此操作,尽管等待时间是正确的,但语句执行的顺序不在我的系统上(带有 g++ 编译器的 Ubuntu 14.04)。我在一个 cout 语句中写了应该在 while 循环之前发生的语句。目前它只在 while 循环之后执行,尽管在我的代码中位于此循环之前。我不确定如何解决这个问题...
//Program to wait a certain number of seconds
//Also introduces the "while" loop
#include <iostream>
#include <ctime>
int main()
{
using namespace std;
float seconds;
cout << "\nEnter the number of seconds you wish to wait for: ";
cin >> seconds;
cout << "\n\nStarting countdown...\a";
//clock_t is a variable type! It's in terms of system clock units though, NOT seconds
clock_t delay = seconds * CLOCKS_PER_SEC;
clock_t start = clock();
while (clock() - start < delay);
cout <<"\a and done!\n\n";
return 0;
}
输入等待的秒数后,我得到的输出是系统在我输入的时间内闪烁光标,然后是“开始倒计时……完成!”一次全部。有什么想法吗?
【问题讨论】:
-
cout被缓冲。使用cout.flush()确保已打印整个缓冲区。
标签: c++ while-loop execution statements