Good() and fail() understanding

Input: 10 20 30
Output: 60

Input: 10 a 20
Output: 10

Because it got somethings that is not a number. And I cant understand how good() and fail() work here.

int sum(istringstream & text) noexcept {
    int sum = 0; 
    int current = 0; 
    while (text.good())
    {
        text >> current; 
        if (!text.fail())
        {
            sum += current;
        }
    }
    return sum;
}

Upvotes: 0

Views: 1047

Answers (1)

lenz
lenz

Reputation: 2425

Fail

You try to read something that is not a number into an integer. This will trigger the failbit in your stringstream. The failbit basically prevents you from using that stream altogether (consider your stream "broken"). The failbit will remain on until the object is destroyed OR until you manually remove it with text.clear().


std::ios::fail
Check whether either failbit or badbit is set
Returns true if either (or both) the failbit or the badbit error state flags is set for the stream.
At least one of these flags is set when an error occurs during an input operation.

failbit is generally set by an operation when the error is related to the internal logic of the operation itself; further operations on the stream may be possible.

Also check out this table enter image description here

If you look at the fail() column under "functions to check state flags", you'll see that fail() returns true under 2 conditions:

  1. Logical error on i/o operation
  2. Read/writing error on i/o operation (Your case)

Source


Good

As for good(), it checks that there are currently no flags (see table above for the flags).

Returns true if none of the stream's error state flags (eofbit, failbit and badbit) is set.

Upvotes: 1

Related Questions