简体   繁体   中英

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?

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM