2015-01-17 63 views
0
//Stores the line 
string line; 
//create a vector where each element will be a new line 
vector<string> v; 
int counter = 0; 

//While we havent reached the end of line 
while (getline(cin, line) && !cin.eof()) 
{ 
    //get the line and push it to a vector 
    v.push_back(line); 
    counter++; 
for(int i = 0; i <counter; i++) 
    { 
     cout<<v[i]<<endl; 
    } 
} 
    return 0; 
} 

的問題是,怎麼來的,如果我輸入讓說:如何檢測文件結束在C++字符串輸入

Hello 
World (end of file) 

輸出只有:

Hello 

世界不輸出它只輸出你好和世界如果我輸入

Hello 
World 
(end of file) 

很抱歉,如果這是一個非常簡單的問題:/,但如果你有沒有線的一端與EOF結束的行,這我不能算出這個

+5

只要'while(getline(cin,line))'就足夠了。不需要額外的檢查'!cin.eof()'。 –

+3

只要做'while(std :: getline(...))'就足夠了。 ['std :: getline'](http://en.cppreference.com/w/cpp/string/basic_string/getline)函數返回流,它可以用作[布爾表達式](http:// en.cppreference.com/w/cpp/io/basic_ios/operator_bool),當有錯誤或文件結束時它會返回「false」。 –

+1

您正在描述相同的情況:hello world(行尾)! – saadtaame

回答

5

while (getline(cin, line) && !cin.eof()) 

將有getline返回「all ok」,但由於getline已到達文件的實際末尾,因此cin.eof()也是true,這意味着您的循環不會處理輸入的最後一個。

更改代碼,以便它根本:

while (getline(cin, line)) 

,一切都會好起來的。

如果你真的很在乎你實際上是在閱讀整個文件,並且getline沒有出於任何其他原因而失敗,那麼在循環之後使用類似的東西可以確保 - 但我覺得很難想象在這種情況下會發生......

if (!cin.eof()) 
{ 
    cout << "Enexpected: didn't reach end of file" << endl; 
} 
相關問題