Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to see if value entered is a number and not chars?

Tags:

c

scanf

I want to know if someone entered a number and if they did the program continues but if they didn't the program terminates.

int main(void) {
    int i;

    printf("Enter a number: ");
    scanf("%d",&i);
    /*If input is not a number than terminate*/


    /*Otherwise continue*/
    else {
        if (test_prime(i))
            printf("Prime.\n");
        else
            printf("Not prime.\n");
    }
    return 0;
}

If the user enters "hello" than I want program to terminate.

like image 852
kron maz Avatar asked Feb 02 '26 02:02

kron maz


1 Answers

Well the right way to do it will be something like this

int main(void) {
    int i;

    printf("Enter a number: ");
    if( scanf("%d",&i) != 1){
        fprintf(stderr,"%s\n","Error in input, input is not number");
        exit(1);
    }
    /*input is a number */
    
    if (test_prime(i))
       printf("%s\n","Prime.");
    else
       printf("%s\n","Not prime.");
    
    return 0;
}

Checking the return value of scanf will help us know whether the scanf call was successful or not.

Alternatively you can use fgets() to get a line input and then parse it and check with functions like strtol etc. Checking whether the input is a correct number with only applying isdigit() on it is not a solution.(As provided in other answer). You can check by giving an input 1234 and you will see the isdigit() solution fails here though it shouldn't.

To give you an idea why the isdigit solution won't work, from 7.4.1.5 standard we can see the quote

The isdigit function tests for any decimal-digit character.

And the decimal digit characters are 0,1...9.

Explanation of the solution provided:

If you look into the return value of the function it says

the function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.

This is what is being checked. And this works for multiple digit number also.

like image 139
user2736738 Avatar answered Feb 04 '26 01:02

user2736738



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!