简体   繁体   中英

c check integer

I'm finding a function to check digit in c, is isdigit only check 0-9 ? how about 10-99999?

i have an integer, eg 22, i want to check is it valid?

any ideas? thanks~

isdigit et. al are for checking characters. 10-99999 is no longer a single character. If you want to check that the string "8382820" is numeric, you have (at least) 3 options:

  • Loop over the string, and run isdigit on each character (failing if one of them isn't)
  • Use a regular expression ( "^[0-9]+$" should do the trick, but not very practical in C)
  • Use strtol and check that the end pointer is the null terminator.

Here's an idea of how to use strtol:

char* myString = "9823872";
char* endPtr = NULL;
long int myInt = strtol(myString, &endPtr, 10);

if(endPtr && *endPtr != '\0')
{
    fprintf(stderr, "Sorry, that's not a valid number\n");
    exit(1);
}

There are probably other clever answers involving scanf or atoi, but I'll just leave it at this for now.

The isdigit() function checks one character at a time. If you want to check more than one character from a string, loop over the characters in the string and call isdigit() on each one.

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