assignment_operator
assignment_operator

Reputation: 1365

getline(cin,input) with multiple lines? (C++)

I'm having an issue here that's giving me a hard time. So, I've got to read something in the format [please read the body as well, to understand my issue a little better]:

               TITLE

The text is actually from a file being redirected 
to input stream via piping in linux bash. I cannot
use ifstream or anything other than some form of cin,
of which I believe getline to be the most useful. 

etc.

Specifically, what's giving me a hard time is the blank space between TITLE and the body. I can't seem to think of a way to work around that using getline(cin,string).

The best I've come up with:

while(inputString.size() != 0)
    getline(cin,inputString);
    //process string

... is thrown out the window with the above-mentioned blank line.

Any ideas, guys?

Thanks!

Upvotes: 4

Views: 21438

Answers (2)

Eitan T
Eitan T

Reputation: 32930

I think the real issue here is your logic. Your input contains both empty and non-empty lines, so if you want to read all of them, you shouldn't rely on the length of the line. This can be done by testing the stream returned by std::getline, like so:

while (getline(cin, inputString))
{
    // Do something with inputString...
}

The loops reads from cin line by line and stops when it reaches the end of the input.

Upvotes: 6

john
john

Reputation: 87959

Should be

while(inputString.size() == 0)

You carry on reading while the string has size 0.

For extra clarity try this instead

while(inputString.empty())

Upvotes: 0

Related Questions