Loop until integer input is in required range fails to work with non-digit character inputs

后端 未结 4 1328
没有蜡笔的小新
没有蜡笔的小新 2020-12-01 17:25

I\'m having a problem with what should be incredibly simple code. I want to take in an integer between 1 and 3 with error checking. It works fine for checking for numbers

4条回答
  •  北海茫月
    2020-12-01 18:10

    Most of these answers include unnecessary complexity.

    Input validation is a perfect time to use a do-while

    do{
    
       cout << "\nPlease enter a number from 1 to 3:" << endl;
       cout << "-> ";
    
       if(!cin){
          cout << "Invalid input"
          cin.clear()
          cin.ignore(numeric_limits::max(), '\n');
       }
    
    }while(!(cin >> input))
    
    • Use numeric_limits::max() to completely clear the buffer after a failed cin.

    • Use cin.clear() to reset the fail flag on cin so !cin wont always evaluate false.

    cin.fail() is fine. However some would consider !cin more natural.

    from my previous post https://stackoverflow.com/a/43421325/5890809

提交回复
热议问题