How do I prevent a runaway input loop when I request a number but the user enters a non-number?

前端 未结 6 821
名媛妹妹
名媛妹妹 2020-12-11 09:03

I need to know how to make my cin statement not appear to \'remove\' itself if you input the wrong type. The code is here:

int mathOperator()
{
  using names         


        
6条回答
  •  我在风中等你
    2020-12-11 09:43

    Unless you're quite certain about the input being in the proper format, you rarely want to use operator>> directly from the input stream.

    It's usually easier to read a line with std::getline, put that into a std::istringstream, and read from there. If that fails, you print/log an error message, throw away the remainder of the line and (possibly) go on to the next line.

提交回复
热议问题