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

前端 未结 6 809
名媛妹妹
名媛妹妹 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

    After reading in a bad value, cin is in a "failed" state. You have to reset this.

    You must both clear the error flag and empty the buffer. thus:

       cin.clear(); 
       cin.ignore(std::numeric_limits::max(), '\n');
    

    The second call "flushes" the input buffer of any data that might be there, to get you ready for the next "cin" call.

    If you find yourself writing these 2 lines "all over your code" you could write a simple inline function to replace it.

       inline void reset( std::istream & is )
       {
           is.clear();
           is.ignore( std::numeric_limits::max(), '\n' );
       }
    

    Although I have made this function take any istream, most of the time it would only be used for cin where a user is entering and enters something invalid. If it's an invalid file or stringstream input, there is no way to fix it and you would do best to just throw an exception.

提交回复
热议问题