user53670
user53670

Reputation:

How to determine whether it is EOF when using getline() in c++?

string s;
getline(cin,s);

while (HOW TO WRITE IT HERE?)
{
    inputs.push_back(s);    
    getline(cin,s);
}

Upvotes: 2

Views: 8627

Answers (2)

Tom
Tom

Reputation: 45174

string s;
getline(cin,s);

while (!cin.eof)
{
        inputs.push_back(s);    
        getline(cin,s);
}

Upvotes: 1

coppro
coppro

Reputation: 14526

Since I'm too lazy to give a full answer today, I'll just paste what the really useful bot in ##c++ on Freenode has to say:

Using "while (!stream.eof()) {}" is almost certainly wrong. Use the stream's state as the tested value instead: while (std::getline(stream, str)) {}. For further explanation see http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.5

In other words, your code should be

string s;

while (getline(cin, s))
{
    inputs.push_back(s);    
}

Upvotes: 8

Related Questions