秒; cout,c++,while-loop,execution,statements,C++,While Loop,Execution,Statements" /> 秒; cout,c++,while-loop,execution,statements,C++,While Loop,Execution,Statements" />

而循环在C++; 我从第5章写了一个简单的程序,从C++入门第五版中列出了5.14,它的意思是从用户那里输入一个输入时间,使程序在几秒钟内等待“时间”。该程序使用while循环执行,尽管等待时间正确,但语句的执行顺序不在我的系统上(Ubuntu14.04和g++编译器)。我写了一个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; } //程序等待一定的秒数 //还介绍了“while”循环 #包括 #包括 int main() { 使用名称空间std; 浮动秒; cout>秒; cout

而循环在C++; 我从第5章写了一个简单的程序,从C++入门第五版中列出了5.14,它的意思是从用户那里输入一个输入时间,使程序在几秒钟内等待“时间”。该程序使用while循环执行,尽管等待时间正确,但语句的执行顺序不在我的系统上(Ubuntu14.04和g++编译器)。我写了一个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; } //程序等待一定的秒数 //还介绍了“while”循环 #包括 #包括 int main() { 使用名称空间std; 浮动秒; cout>秒; cout,c++,while-loop,execution,statements,C++,While Loop,Execution,Statements,您想刷新cout的缓冲区,比如: cout << "\n\nStarting countdown...\a" << endl; 在输出之后;输出流将缓冲其输出,直到刷新为止。您可以手动刷新它,以确保在预期时看到输出: cout << "\n\nStarting countdown...\a" << flush; cout您也可以简单地输出到cerr而不是cout,这样就不需要显式刷新,因为它会自动刷新。cout是缓冲的。使用cout.flush

您想刷新cout的缓冲区,比如:

cout << "\n\nStarting countdown...\a" << endl;

在输出之后;

输出流将缓冲其输出,直到刷新为止。您可以手动刷新它,以确保在预期时看到输出:

cout << "\n\nStarting countdown...\a" << flush;

cout您也可以简单地输出到
cerr
而不是
cout
,这样就不需要显式刷新,因为它会自动刷新。

cout
是缓冲的。使用
cout.flush()
以确保已打印整个缓冲区。太好了!非常感谢。但是
cerr
cout
不一样。
cout.flush();
cout << "\n\nStarting countdown...\a" << flush;