Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read an unknown number of lines from console in c++

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);
like image 672
Sachin Avatar asked Jan 18 '23 09:01

Sachin


2 Answers

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);
}
like image 125
Luchian Grigore Avatar answered Jan 23 '23 14:01

Luchian Grigore


Try:

vector<string> file;    
string line;
while( getline(cin,line))
{
    if( line.empty())
        break;
    file.push_back(line);
}
like image 41
nickb Avatar answered Jan 23 '23 14:01

nickb