对于交错的cout和cin操作,显式刷新是必需的吗

Is explicit flush necessary for interleaved cout and cin operations?

本文关键字:刷新 cout 于交错 cin 操作      更新时间:2023-10-16

我注意到,在许多源代码文件中,可以看到在读取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::coutstd::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;
}

标准流操作是通过这种方式实现的。如果用户的输入操作不是以这种风格实现的,而是直接使用流缓冲区进行输入,则不会发生刷新。当然,错误出现在输入运算符中。