2015-03-03 70 views
1
vector<string> svec; 
    string str; 
    while (cin >> str&&!cin.eof()) 
    { 
     svec.push_back(str); 
    } 
    for (auto c:svec) 
    { 
     cout << c << " "; 
    } 

如果我輸入tt tt tt,則輸出爲tt tt tt。 但是,如果我什麼都沒輸入,我輸入Ctrl + Z(windows + vs2013)會崩潰。 所以我嘗試修復它。如果我輸入「Ctrl + Z」,它會崩潰,如何修復它?

while (!cin.eof()) 
    { 
     cin >> str; 
     svec.push_back(str); 
    } 

現在,如果我輸入什麼,我鍵入按Ctrl +ž不會崩潰。 但是,如果我輸入tt tt tt,輸出是tt tt tt tt

現在我不知道如何解決它。請幫幫我 。

+1

做您使用調試器來查看它崩潰的位置?也使用stringstream而不是'std :: cin'可能是一個好主意,你可以用EOF填充stringstream。另見http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong – holgac 2015-03-03 07:57:07

+0

'&&!cin.eof()'是多餘的。 'operator >>'將返回流對象,當它到達EOF時,流對象的計算結果爲'false'。 – 2015-03-03 08:21:17

回答

1

你應該嘗試只是:

while (cin >> str) 
{ 
    svec.push_back(str); 
} 

爲什麼額外TT
如果我解開你的while循環,這是不言而喻的:

1. buf [tt tt tt, not eof], vec [] 
    a. is eof no 
    b. read and push str 
2. buf [tt tt, not eof], vec [tt] 
    a. is eof no 
    b. read and push str 
3. buf [tt, not eof], vec [tt tt] 
    a. is eof no 
    b. read and push str 
4. buf [, not eof], vec [tt tt tt] 
    a. is eof no 
    b. read and push str [read fails, str contains old value and eof is set] 
5. buf [eof], vec [tt tt tt tt] 
    a. is eof yes 
    b. break 

您還可以閱讀Why while(!feof(...)) is almost always wrong

+0

我在vs2013中試過了你的代碼,如果我沒有輸入,然後輸入'ctrl + z',它仍然會崩潰,那麼你能給我其他建議嗎? – Ocxs 2015-03-03 12:04:37

+0

你可以嘗試'do {if(cin >> str)svec.push_back(str);} while(!cin.eof())''。儘管我認爲額外檢查是多餘的,您應該嘗試找出崩潰的來源。 – 2015-03-03 12:12:10

+0

我試過了,它也墜毀了。如果我在'while'中使用'!cin.eof()'(而不是'do {} while'),它不會崩潰。但作爲你的[鏈接](http://stackoverflow.com/questions/5431941/ while-feof-file-is-always-wrong)說,**它比作者期望的多一次進入循環。如果有讀取錯誤,循環不會終止。**。如果我不使用cin.eof(),它會崩潰。 – Ocxs 2015-03-03 12:32:06

相關問題