Read an unknown number of lines from console in c+

2019-06-23 17:28发布

问题:

I am using the following loop to read an unknown number of lines from the console, but it is not working. After I have fed the input I keeping pressing enter but the loop does not stop.

vector<string> file;    
string line;
while(getline(cin,line)
    file.push_back(line);

回答1:

Because getline will evaluate to true even if you push only enter.

You need to compare the read string to the empty string and break if true.

vector<string> file;    
string line;
while(getline(cin,line))
{
    if (line.empty())
       break;
    file.push_back(line);
}


回答2:

For getline is easy, as it is suggested by other answers:

string line;
while(getline(cin,line))
{
    if (line.empty())
       break;
    file.push_back(line);
}

But to cin objects, I found a way to without the need for any breaking character. You have to use the same variable to cin all of the objects. After usage, you need to set it to a default exit value. Then check if your variable is the same after the next cin. Example:

string o;
while(true){
    cin>>o;
    if (o.compare("tmp")==0)
        break;
    // your normal code
    o="tmp";
}


回答3:

Try:

vector<string> file;    
string line;
while( getline(cin,line))
{
    if( line.empty())
        break;
    file.push_back(line);
}


回答4:

You should signal the end of file to your application. On Linux it is Ctrl-D, and it might be Ctrl-Z on some Microsoft systems

And your application should test of end of file condition using eof()