【发布时间】:2013-12-16 02:49:31
【问题描述】:
我注意到,在许多源代码文件中,可以看到在读取 cin 之前写入 cout 没有显式刷新:
#include <iostream>
using std::cin; using std::cout;
int main() {
int a, b;
cout << "Please enter a number: ";
cin >> a;
cout << "Another nomber: ";
cin >> b;
}
当它执行并且用户输入42[Enter]73[Enter] 时,它会很好地打印出来(g++ 4.6,Ubuntu):
Please enter a number: 42
Another number: 73
这是已定义的行为吗,即标准是否规定在读取 cin 之前以某种方式刷新了 cout?我可以在所有符合标准的系统上预期这种行为吗?
或者应该在这些消息之后添加一个显式cout << flush?
【问题讨论】: