【问题标题】:Is explicit flush necessary for interleaved cout and cin operations?交错的 cout 和 cin 操作是否需要显式刷新?
【发布时间】:2013-12-16 02:49:31
【问题描述】:

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

【问题讨论】:

    标签: c++ stream iostream flush


    【解决方案1】:

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

    标准的流操作就是这样实现的。当用户的输入操作没有以这种方式实现并且直接使用流缓冲区进行输入时,刷新不会发生。当然,错误在于输入运算符。

    【讨论】:

      猜你喜欢
      • 2021-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-11
      相关资源
      最近更新 更多