1

Note:The code works fine and the o/p is desired too I just wanna know does cout displays into the screen or writes to ostream,and if it writes to ostream when does the ostream gets displayed .

I have following c++ code

#include<iostream>
#include<string>
#include<cctype>

using namespace std;

int main()
{
string str,buffer;
while(cin)//take input forever
{
cin>>str;
if(str =="Quit")//unless the word is Quit
{
break;
}
else{
if(buffer != str)//donot repeat the words
 {
 cout<<str<<" ";
 }
}
buffer = str;
}
 return 0;
}

Why is not str being displayed everytime str != "Quit"?Is it because of the fact that cout doesnot display something in the screen it just writes or sends them to the ostream and ostream is responsible for something to be displayed.

If that is true,When does the ostream gets displayed in the screen -after inputting to the stream is finished?

IcanCode
  • 237
  • 9
  • [Code works fine here](https://wandbox.org/permlink/FPa5ovw4KmkjF6MM) – NathanOliver Feb 26 '21 at 13:17
  • @NathanOliver Yeah it works fine,I just want to know what is happening behind?Hope the question is clear!!! – IcanCode Feb 26 '21 at 13:20
  • 1
    `while(cin)`... please don't. This is a variation of the awkward [while eof](https://stackoverflow.com/q/5605125/3545273) and is (almost) always wrong. It is wrong here. – Serge Ballesta Feb 26 '21 at 13:21
  • See https://stackoverflow.com/questions/22026751/c-force-stdcout-flush-print-to-screen – jarmod Feb 26 '21 at 13:25
  • cout is not a function, it's an object – szpanczyk Feb 26 '21 at 14:01
  • 1
    also, please pay more attention to indentation, verical and horizontal spaces etc., make your code look neat, orderly and thus readable. It's way more important than you think, it's not just aesthetics. – szpanczyk Feb 26 '21 at 14:02

1 Answers1

1

Here is what you code does

Is there already an error/eof on cin? if yes get out
read something
if it is Quit IMMEDIATELY GET OUT
other operations

So when you type Quit it is not printed, simply because you never ask for this.

But that is not all. On an eof condition here is what happens:

Is there already an error/eof on cin: not yet...
read something
find the eof and note it for later, but do not change str
is str Quit? No it was not and nothing has changed
compare str to buffer and find that they are equal
set buffer to str (again...)
go back to the beginning of the loop
Is there already an error/eof on cin: Yep there is!
exit loop

So you do an additional useless round trip. It would be better to test cin immediately after the read:

for(;;) {
    cin >> str;
    if (!cin) break;
    ...
}
Serge Ballesta
  • 121,548
  • 10
  • 94
  • 199