Flushing of cout prior to reading input using cin .. why?

前端 未结 2 952
轮回少年
轮回少年 2020-12-18 14:52

Why does cout has to be flushed before cin starts reading? Aren\'t they of different buffer? I can have reading of input into a buffer while same time putting it on output b

相关标签:
2条回答
  • 2020-12-18 15:00

    It doesn't have to be flushed. By default the streams are tied together so that when you do things like:

    cout << "Enter your name:";
    cin >> name;
    

    the prompt appears before the input starts - this is just a convenience feature. However, you can untie them:

    cin.tie( static_cast<ostream*>(0) );
    

    following which cout will not (necessarily) be flushed before input is performed on cin.

    0 讨论(0)
  • 2020-12-18 15:06

    The canonical example is this:

     std::cout << "Enter your name: ";
     std::string name;
     std::cin >> name;
    

    You do want to see the prompt before the input, that's why those two streams are tied together.

    0 讨论(0)
提交回复
热议问题