2015-01-17 44 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; 
} 
相关问题