我注意到在许多源代码文件中,人们可以看到cout
在cin
没有显式刷新的情况下在写入之前写入:
#includeusing 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
?
默认情况下,流std::cout
被绑定std::cin
:指向的流stream.tie()
在每次正确实现输入操作之前被刷新.除非您更改了绑定的流std::cin
,否则std::cout
在使用之前无需刷新,std::cin
因为它将隐式完成.
在std::istream::sentry
使用输入流构造a时,会发生刷新流的实际逻辑:当输入流未处于故障状态时,stream.tie()
刷新指向的流.当然,这假设输入运算符看起来像这样:
std::istream& operator>> (std::istream& in, T& value) { std::istream::sentry cerberos(in); if (sentry) { // read the value } return in; }
标准流操作以这种方式实现.当用户的输入操作未以此样式实现并使用流缓冲区直接进行输入时,不会发生刷新.当然,错误在输入操作符中.