input validation for numeric input

后端 未结 2 1248
迷失自我
迷失自我 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条回答
  • 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<std::streamsize>::max()); 
            std::cout << "Incorrect, must be numeric: " << std::endl;
        }
        return i;
     }
    
    0 讨论(0)
  • 2020-12-22 05:15

    This looks like line oriented input. In which case, the usual solution is to use getline:

    bool parseNumber( std::string const& text, int& results )
    {
        std::istringstream parser( text );
        return parser >> results >> std::ws && parser.peek() == EOF;
    }
    
    int getNumber()
    {
        int results;
        std::string line;
        while ( ! std::getline( std::cin, line ) || ! parseNumber( line, results ) ) 
        {
            std::cin.clear();
            std::cout << "Only 'numeric' value(s) allowed:";
        }
        return results;
    }
    
    0 讨论(0)
提交回复
热议问题