簡體   English   中英

`cout` function 如何在 c++ 中實際工作?

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

注意:代碼工作正常,o/p 也是需要的

我有以下 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;
}

為什么str每次都不顯示str != "Quit" ?是因為cout不會在屏幕上顯示某些內容,它只是寫入或將它們發送到 ostream 並且 ostream 負責顯示某些內容。

如果這是真的,當輸入到 stream 完成后,ostream 什么時候顯示在屏幕上?

這是您的代碼所做的

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;
    ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM