我注意到,在许多源代码文件中,可以看到在从cout读取之前没有显式刷新而写入cin:
#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这是定义的行为吗,即标准是否说cout 在 cin 读取之前就被刷新了?我能期望在所有符合标准的系统上出现这种行为吗?
还是应该在这些消息之后添加一个cout << flush 显式?
发布于 2013-11-29 21:40:04
默认情况下,流std::cout绑定到std::cin:在每个正确实现的输入操作之前,stream.tie()指向的流都会被刷新。除非您更改了绑定到std::cin的流,否则在使用std::cin之前不需要刷新std::cout,因为这将是隐式的。
使用输入流构造std::istream::sentry时会发生刷新流的实际逻辑:当输入流没有处于失败状态时,stream.tie()所指向的流被刷新。当然,这假设输入运算符如下所示:
std::istream& operator>> (std::istream& in, T& value) {
std::istream::sentry cerberos(in);
if (sentry) {
// read the value
}
return in;
}标准的流操作就是这样实现的。当用户的输入操作没有以这种方式实现,并且直接使用流缓冲区进行输入时,就不会发生刷新。当然,错误是输入运算符中的错误。
https://stackoverflow.com/questions/20293679
复制相似问题