Home > Net >  How to use isdigit function to check whether a given multiple digit character is numeric or not?
How to use isdigit function to check whether a given multiple digit character is numeric or not?

Time:01-14

How to use isdigit function in C to check whether the given multiple digit string is numeric or not? This is how I used isdigit function for a single digit character.

#include<stdio.h>
#include<cs50.h>
#include<ctype.h>
int main()
{
    char c = get_char("Enter a single character:");
    int a = isdigit(c);
    if ( a != 0)
    {
        printf("%c is an integer \n", c);
    }
    else
    {
        printf("%c is not an integer \n",c);
    }
}

Now, I want to check for the multiple digit character(eg. 92, 789). here is my code

#include<stdio.h>
#include<cs50.h>
#include<string.h>
#include<ctype.h>
int main()
{
    string num = get_string(" Enter a number:");
    int final = 1;
    for(int i =0; i< strlen(num); i  )
    {
      // final = final * isdigit(num(i));
      final*= isdigit(num[i]);
    }
    if(final!=0)
    {
        printf("%s is an integer.\n", num);
    }
    else
    {
        printf("%s is not an integer.\n", num);
    }
}

However, the above code only works for two digit integer , but not for 3 digit integer. See this: Compiled Code SS

CodePudding user response:

The isdigit function isn't required to return a boolean 0 or 1 value. It's specified to return zero if the character isn't a digit, and any non-zero value if it is a digit.

Take for example the implementation used by here. We can see that isdigit returns 2048.

Because it returns that value, the multiplication will lead to a signed integer arithmetic overflow, which in turn leads to undefined behavior.

Instead I suggest you use isdigit directly in a condition, and if it returns 0 then print the message and terminate the program:

size_t length = strlen(num);
if (length == 0)
{
    printf("String is empty\n");
    return EXIT_FAILURE;
}

for (size_t i = 0; i < length;   i)
{
    if (isdigit(num[i]) == 0)
    {
        printf("Input was not a number\n");
        return EXIT_FAILURE;
    }
}

// Here we know that all characters in the input are digits

CodePudding user response:

You could simply replace the multiply operation with &... Once a non-digit appears and isdigit() returns 0 (meaning false), the flag variable will remain false.

You may want to consider combining operations into compact code such as the following.

#include <stdio.h>
#include <ctype.h>
#include <cs50.h> // less "generic" that the others

int main( void ) {
    string num = get_string(" Enter a number:");

    int i = 0;
    while( isdigit( num[i] ) ) i  ; // loop fails on '\0', too

    if( i == 0 || num[i] ) // empty string or did not reach its end
        printf( "%s is NOT an integer.\n", num );
    else
        printf( "%s is an integer.\n", num );

    return 0;
}
  • Related