对于交错的cout和cin操作,显式刷新是必需的吗
Is explicit flush necessary for interleaved cout and cin operations?
我注意到,在许多源代码文件中,可以看到在读取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
?
默认情况下,流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;
}
标准流操作是通过这种方式实现的。如果用户的输入操作不是以这种风格实现的,而是直接使用流缓冲区进行输入,则不会发生刷新。当然,错误出现在输入运算符中。
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- std::cout.imbue()多重调用
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 在 COUT 语句中使用 COUT 调用函数
- GCC 4.8.2 自动矢量化由于 cout 而失败
- 是否可以配置提升日志刷新?
- 如何在qt中同步应用程序和显示器的刷新率?
- std::cout输出int时出现编译错误
- 在这种情况下显式调用时,std::cout 如何更改析构函数的行为?
- 如何让 cout 缓冲区在 ubuntu 上刷新
- 如何制作一个简单的C++程序,其中std::cout不被刷新
- C++ 强制 std::cout 刷新(打印到屏幕)
- 对于交错的cout和cin操作,显式刷新是必需的吗
- 获取文件数据后刷新 cout 的问题
- 为什么' '会刷新std::cout
- cout 不会打印C++字符串(包括<iostream>、包含<string>和刷新所有存在的内容)
- 捕获和引发 std::cout 刷新事件上的事件