交替使用cout和cin时,是否需要显式刷新缓冲区?

4
我注意到在许多源代码文件中,可以看到在从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 呢?

1个回答

9
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;
}

标准流操作是这样实现的。当用户的输入操作没有采用这种风格,并且直接使用流缓冲区进行输入时,将不会发生刷新。错误显然在输入操作符中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接