What happens when >> operator is trying to input a value bigger than a variable can contain?

前端 未结 3 953
花落未央
花落未央 2021-01-19 16:05

I\'m pulling numbers from a text file and filling an array of type int with them.

I\'m inserting the values into the array while looping through the .txt file with t

3条回答
  •  盖世英雄少女心
    2021-01-19 16:16

    The standard requires that if the input value is out of range, the nearest available value is written to the destination, and the stream's failbit is set. The specific requirement (from [istream.formatted.arithmetic]/3) is:

    operator>>(int& val);
    

    The conversion occurs as if performed by the following code fragment [...]:

    iostate err = ios_base::goodbit;
    long lval;
    use_facet(loc).get(*this, 0, *this, err, lval);
    if (lval < numeric_limits::min()) {
        err |= ios_base::failbit;
        val = numeric_limits::min();
    }
    else if (numeric_limits::max() < lval) {
        err |= ios_base::failbit;
        val = numeric_limits::max();
    }
    else
        val = static_cast(lval);
    setstate(err);
    

    Once the stream's failbit is set, it's "sticky", so further attempts at extracting data will all fail immediately until the failbit is cleared.

提交回复
热议问题