Check if the input is a number or string in C++

前端 未结 7 492
没有蜡笔的小新
没有蜡笔的小新 2020-12-10 06:16

I wrote the following code to check whether the input(answer3) is a number or string, if it is not a number it should return \"Enter Numbers Only\" but it returns the same e

7条回答
  •  失恋的感觉
    2020-12-10 06:46

    You can use regex to do this:

    #include 
    
    bool isNumber(std::string x){
        std::regex e ("^-?\\d+");
        if (std::regex_match (x,e)) return true;
        else return false;}
    

    If you want to make isNumber() a generic function which can take any type of input:

    #include 
    #include 
    
    template
    bool isNumber(T x){
        std::string s;
        std::regex e ("^-?\\d+");
        std::stringstream ss; 
        ss << x;
        ss >>s;
        if (std::regex_match (s,e)) return true;
        else return false;}
    

    The above isNumber() function checks for integer only, double or float value with precision (which contains dot .) will not return true. If you want precision too, then change the regex line to:

    std::regex e ("^-?\\d*\\.?\\d+");
    

    If you want a more efficient solution, see this one.

提交回复
热议问题