input validation for numeric input

后端 未结 2 1249
迷失自我
迷失自我 2020-12-22 04:51

I\'m very new to this C++ world and trying write a input validation function for numeric password. This is what I got so far:

#include 
#incl         


        
2条回答
  •  旧时难觅i
    2020-12-22 05:04

    If there is a failure to convert then the stream itself evaluates to false so you can do this:

    int get_int() {
        int i;
        std::cout << "Please enter a number: " << std::endl;
        while(!(std::cin >> i)) {
            std::cin.clear();   //clear flags
            //discard bad input
            std::cin.ignore(std::numeric_limits::max()); 
            std::cout << "Incorrect, must be numeric: " << std::endl;
        }
        return i;
     }
    

提交回复
热议问题