Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading