How does istream::ignore( ) work?

后端 未结 1 363
無奈伤痛
無奈伤痛 2020-12-07 05:29

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

1条回答
  •  太阳男子
    2020-12-07 06:10

    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::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.

    0 讨论(0)
提交回复
热议问题