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);
Try:
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.For
getline
is easy, as it is suggested by other answers: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: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()