wrongusername
wrongusername

Reputation: 18918

Entering values from stringstream

Is there a while loop that allows me to enter in all the values for a stringstream into some datatype? For example:

stringstream line;
while(/*there's still stuff in line*/)
{
    string thing;
    line >> thing;
    //do stuff with thing
}

Upvotes: 2

Views: 2123

Answers (1)

James McNellis
James McNellis

Reputation: 355069

Yes:

std::stringstream line;
std::string thing;
while (line >> thing)
{
    // do stuff with thing
}

if (line.fail())
{
    // an error occurred; handle it as appropriate
}

Stream operations (like >>) return the stream; this is what allows you to chain stream operations, like:

line >> x >> y >> z

A stream can be used as a boolean; if the stream is in a good state (that is, if data can be read from it), it evaluates to true; otherwise it evaluates to false. This is why we can use the stream as the condition in the loop.

There are a number of reasons a stream will not be in a good state.

One of them is when you reach the end of the stream (indicated by testing line.eof()); obviously, if you're trying to read all the data out of the stream, this is the condition you expect the stream to be in when you are done.

The other two reasons a stream will not be in a good state are if some internal error or if an operation on the stream failed (for example, if you try to extract an integer but the next data in the stream does not represent an integer). Both of these are tested by line.fail().

Upvotes: 2

Related Questions