如何在C++中检测字符串输入的文件结尾

0 c++ string input

//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;
}
Run Code Online (Sandbox Code Playgroud)

问题是,如果我输入怎么说让我们说:

Hello
World (end of file)
Run Code Online (Sandbox Code Playgroud)

输出仅为:

Hello
Run Code Online (Sandbox Code Playgroud)

如果我输入,则不输出世界只输出Hello和World

Hello
World
(end of file)
Run Code Online (Sandbox Code Playgroud)

对不起,如果这是一个非常简单的问题:/但我无法弄清楚这一点

Mat*_*son 5

如果您的行以EOF结尾而没有行尾,则:

while (getline(cin, line) && !cin.eof())
Run Code Online (Sandbox Code Playgroud)

getline返回"all ok",但由于getline到达文件的实际结尾,cin.eof()true意味着你的循环不会处理输入的最后一个.

更改代码,以便它只是:

while (getline(cin, line))
Run Code Online (Sandbox Code Playgroud)

一切都会好的.

如果你真的在乎你实际上是在阅读整个文件,并且getline没有因某些任意的其他原因而失败,那么在循环之后使用这样的东西可以确保 - 但我发现很难想到会发生这种情况的情况...

if (!cin.eof()) 
{
    cout << "Enexpected: didn't reach end of file" << endl;
}
Run Code Online (Sandbox Code Playgroud)