Seila
Seila

Reputation: 61

Using return value of extraction operator in condition?

Why ss >> aa >> bb >> cc >> dd could be used in condition check ? If i use ss >> aa >> bb >> cc >> dd >> ee what's the return value of this operation ?

ifstream inputFile("source.txt", ifstream::in);
string aa, bb, cc, dd;
char line[1024];

while(!inputFile.eof())
{
    inputFile.getline(line, 1023);
    stringstream ss(stringstream::in | stringstream::out);
    ss.str(line);

    if(ss >> aa >> bb >> cc >> dd)
    {
        cout << aa << "-" << bb << "-" << cc << "-" << dd << endl;
    }
}

With source.txt like this:

1aaa ddd eee asd
2dfs dfsf sdfs fd     
3sdf sdfsdfsdf d s

Upvotes: 1

Views: 1157

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409216

The return value of a stream input operation is the stream.

The expression

ss >> aa

is equal to

operator>>(ss, aa)

and the operator>>() function returns the first argument.

Using multiple input operations simply chains the function calls. For example

ss >> aa >> bb;

becomes

operator>>(ss, aa).operator>>(ss, bb);

The reason a stream can be use as a boolean expression, is because it has a special conversion operator that allows it to be used as such.


By the way, you shouldn't use while (!stream.eof()). Instead use the fact that getline returns the stream, and that a stream can be used in boolean expressions:

while (inputFile.getline(line, 1023))
{
    // ...
}

Upvotes: 5

Related Questions