Ci3
Ci3

Reputation: 4842

How does istream::ignore(std::numeric_limits<std::streamsize>::max(), '\n' ) work?

I've been reading about istream::ignore( ) here. I think I get the main idea of the function it does, but I've seen some examples of accepting only numeric input that uses this function, and I'm not sure why it works.

Why would this code ignore everything except numeric input?

#include <iostream>
#include <sstream>
#include <limits>

int main()
{
    std::istringstream input("1\n"
                             "some non-numeric input\n"
                             "2\n");
    for(;;) {
        int n;
        input >> n;

        if (input.eof() || input.bad()) {
            break;
        } else if (input.fail()) {
            input.clear(); // unset failbit
            input.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // skip bad input
        } else {
            std::cout << n << '\n';
        }
    }
}

I had thought that istream::ignore( ) would ignore any and all characters specified by a certain number until the delimiter..

Upvotes: 2

Views: 10565

Answers (1)

us2012
us2012

Reputation: 16253

When input >> n; encounters non-numeric input, it sets the fail flag. The code checks whether it is set (if (input.fail())), and if it is, ignores up to numeric_limits<streamsize>::max() characters, until it hits a newline \n character. Effectively, this means that the rest of the line on which the failure was encountered will be ignored.

Note that this will still read a number at the beginning of a line like "25 asdasf". If the line is "25 asdfasf 26", however, the 25 will be read, but then the failure occurs and the rest of the line is ignored, including the 26 at the end.

Upvotes: 9

Related Questions