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 buffer (before flushing) .. 2 different buffers. I am confused here.
Asked
Active
Viewed 902 times
2 Answers
8
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.
-
What if i do wanna maintain the 'Enter your name:" in the buffer without displaying it and meantime i wanna read? – yapkm01 Apr 24 '10 at 14:19
-
@yapkm01 Like I said - untie them. It seems unlikely you actually do want to do this, however. – Apr 24 '10 at 14:21
-
@yapkm01: If you think this answers your question best, you should accept it. – sbi Apr 24 '10 at 23:44
-
@sbi Another better answer might come along from someone in a different timezone. Please do not pressure people (especially on my behalf) to accept. – Apr 24 '10 at 23:48
-
@Neil: As I understand it, you can always change the accepted answer later. If an answer fits and answers the question, why not accept it? Anyway, I wasn't trying to pressure. I just thought that someone with a rep of 6 might not know the rules well enough and could live with being hinted at them. – sbi Apr 25 '10 at 00:02
7
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.

sbi
- 219,715
- 46
- 258
- 445