Search code examples
c++cinstdstringtypechecking

std::cin>> is digit or string


I have to determine if the input is a digit or a string.

std::string s;
while (std::cin >> s) { 
    if(isdigit(s)){
        //do something with the variable
    }
    else{
        //do something else with the variable
    }
}

For this I get error: no matching function for call to 'isdigit(std::__cxx11::string&)' Could someone propose a method I should use?


Solution

  • isdigit() works on a single character (and indicates if it is a numerical value between '0' and '9'). To check to see if you have a single digit:

    std::string s;
    while (std::cin >> s) { 
        if(s.size() == 1 && isdigit(s[0])){
            //do something with the variable
        }
        else{
            //do something else with the variable
        }
    }
    

    To check to see if all characters are digits...

    std::string s;
    while (std::cin >> s) { 
        bool alldigits = true;
        for(auto c : s) {
           alldigits = alldigits && isdigit(c);
        }
    
        if(alldigits){
            //do something with the variable
        }
        else{
            //do something else with the variable
        }
    }