简体   繁体   English

`cout` function 如何在 c++ 中实际工作?

[英]How does a `cout` function actually works in c++?

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.注意:代码工作正常,o/p 也是需要的

I have following c++ code我有以下 c++ 代码

#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.为什么str每次都不显示str != "Quit" ?是因为cout不会在屏幕上显示某些内容,它只是写入或将它们发送到 ostream 并且 ostream 负责显示某些内容。

If that is true,When does the ostream gets displayed in the screen -after inputting to the stream is finished?如果这是真的,当输入到 stream 完成后,ostream 什么时候显示在屏幕上?

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.因此,当您键入Quit时,它不会被打印出来,仅仅是因为您从不要求这样做。

But that is not all.但这还不是全部。 On an eof condition here is what happens:在 eof 条件下,会发生以下情况:

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:最好在阅读后立即测试cin

for(;;) {
    cin >> str;
    if (!cin) break;
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM