2016-05-05 9 views
0

最後の単語に達した後、空白やヌル文字、ガベージ値などを出力しない理由を理解できません。なぜ文字列を終えた後にも何の影響もありません。stringstreamの奇妙な動作ですか?

#include <iostream> 
#include <string> 
#include <sstream> 
#include <vector> 
using namespace std; 
int main() 
{ 
    stringstream ss("I am going to goa for"); // Used for breaking words 
    string word; // To store individual words 
    while (ss >> word) 
     cout<<word<<"\n"; 
    ss >> word; 
    cout<<word<<endl; 
    ss >> word; 
    cout<<word<<endl; 
    ss >> word; 
    cout<<word<<endl; 
} 

はOUTPUT:あなたは何のエラーをチェックしないようにif(!ss.fail())を追加する必要があり

I 
am 
going 
to 
goa 
for 
for 
for 
for 
+0

ストリームにエラーフラグが設定されています(そのため、whileループは終了しています)。 –

答えて

0

すべてのcout << word << endl;ラインの前には、読み取りの試み次にstringstreamで発生しています。

1

>>が文字列の最後に到達すると、フェイルビットが設定され、さらに読み込みが停止します。

#include <iostream> 
#include <string> 
#include <sstream> 
#include <vector> 
using namespace std; 
int main() 
{ 
    stringstream ss("I am going to goa for"); // Used for breaking words 
    string word; // To store individual words 
    while (ss >> word) 
     cout<<word<<"\n"; 

    word = "END"; 
    ss >> word; 
    cout<<word<<endl; 
    ss >> word; 
    cout<<word<<endl; 
    ss >> word; 
    cout<<word<<endl; 
} 

forはその中に格納されているためです。 failbitがクリアされるまで、stringstreamから読み取られないことがわかるはずのものに変更してください。

出力は次のようになります。

I 
am 
going 
to 
goa 
for 
END 
END 
END 

は詳細についてはstringstreamを参照してください。