C++ “cout”函数在c++;?

C++ “cout”函数在c++;?,c++,C++,注意:代码运行良好,o/p也很理想,我只想知道cout是否显示在屏幕上或写入ostream,以及它是否写入ostream何时显示ostream 我有以下C++代码< /P> #include<iostream> #include<string> #include<cctype> using namespace std; int main() { string str,buffer; while(cin)//take input forever { cin&

注意:代码运行良好,o/p也很理想,我只想知道cout是否显示在屏幕上或写入ostream,以及它是否写入ostream何时显示ostream

我有以下C++代码< /P>

#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;
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
字符串str,缓冲区;
while(cin)//永远接受输入
{
cin>>str;
if(str==“Quit”)//除非单词是Quit
{
打破
}
否则{
if(buffer!=str)//不要重复这些单词
{

cout下面是代码的功能

Is there already an error/eof on cin? if yes get out
read something
if it is Quit IMMEDIATELY GET OUT
other operations
因此,当您键入
Quit
时,它不会被打印出来,因为您从未要求这样做

但这还不是全部。在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
因此,您需要进行一次额外的无用往返。最好在读取以下内容后立即测试
cin

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

@NathanOliver是的,它工作正常,我只是想知道后面发生了什么?希望问题清楚!!!
while(cin)
…请不要。这是尴尬的变体,几乎是总是错的。这里是错的。另外,请注意缩进、真实空格和水平空格等,使您的代码看起来整洁有序,因此可读。这比您想象的更重要,不仅仅是美观。