How can I check if a string is a whole number in C?

Viewed 173

I have recently encountered a problem in which I had a string array inputted by the argv[] to check if it is a whole number or not.

I tried to use isdigit(). However, it returns "20x" as a whole number. I searched a lot, but could not find anything helpful for C language.

Thank you in advance!

2 Answers

[Requires stdbool.h and ctype.h]

bool isWholeNumber(char* num)
{
    // Check if the input is empty
    if (*num == '\0') return false;

    // Ignore the '+' sign if it is explicitly present in the beginning of the number
    if (*num == '+') ++num;

    // Check if the input contains anything other than digits
    while (*num)
    {
        if (!isdigit(*num)) return false;
        ++num;
    }

    // You can add other tests like
       // Ignoring the leading and trailing spaces
       // Other formats of whole number (1.0, 1.00, 001, 1+0i, etc.)
       // etc. (depends on your input format)

    // The input is a whole number if it passes these tests
    return true;
}

This should work for large whole numbers as well.

I hope you got the logic and the way of approaching this task. Simply iterate through each character in the string and validate them according to your need.

You check per character in your char array:

for(int i = 0; i < length; i++){
   ch = charArray[i];
   if('0' <= ch && ch <= '9'){
      // it's a character number (in decimal)
   }
   // you do with other conditions: formated number, .....
}
Related