Why would we call cin.clear() and cin.ignore() after reading input?

后端 未结 4 1978
小蘑菇
小蘑菇 2020-11-21 22:59

Google Code University\'s C++ tutorial used to have this code:

// Description: Illustrate the use of cin to get input
// and how to recover from errors.

#in         


        
4条回答
  •  醉酒成梦
    2020-11-21 23:35

    The cin.clear() clears the error flag on cin (so that future I/O operations will work correctly), and then cin.ignore(10000, '\n') skips to the next newline (to ignore anything else on the same line as the non-number so that it does not cause another parse failure). It will only skip up to 10000 characters, so the code is assuming the user will not put in a very long, invalid line.

提交回复
热议问题