adrianp
adrianp

Reputation: 183

isdigit() is not working?

When I enter a number and test it with isdigit, it always returns false, why?

#include <iostream>

using namespace std;
int main() {

    int num;

    cin >> num;

    if(isdigit(num))
    cout << "Is a number";

    else
    cout << "That is not a number";

}

Sample input: 1

Upvotes: 0

Views: 1894

Answers (1)

Barry
Barry

Reputation: 302852

That's because the intent of isdigit is to check a character for whether or not it's an ASCII digit. For instance:

if (isdigit('4')) {
    // yep
}

Or:

std::string str = "12345";
if (std::all_of(str.begin(), str.end(), isdigit)) {
    // ok this is safe
    int i = std::stoi(str);
}

It is basically checking if its input is between '0' and '9'. Which is to say, 48 and 57. It will return 0 for any other value.

Upvotes: 2

Related Questions