Home > Software design >  std::cin>> is digit or string
std::cin>> is digit or string

Time:09-27

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?

CodePudding user response:

is digit works on chars (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
    }
}
  • Related