input validation for numeric input

后端 未结 2 1247
迷失自我
迷失自我 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: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;
    }
    

提交回复
热议问题