Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a value from scanf is a number?

Tags:

c

In the simplest way possible, how can I check if an integer initialized from function scanf is a number?

like image 526
genesisxyz Avatar asked Jan 07 '10 19:01

genesisxyz


People also ask

How do you check if a input is an integer?

Input the data. Apply isdigit() function that checks whether a given input is numeric character or not. This function takes single argument as an integer and also returns the value of type int.


1 Answers

http://www.cplusplus.com/reference/clibrary/cstdio/scanf/

On success, [scanf] returns the number of items succesfully read. This count can match the expected number of readings or fewer, even zero, if a matching failure happens. In the case of an input failure before any data could be successfully read, EOF is returned.

So you could do something like this:

#include <stdio.h>

int main()
{
    int v;
    if (scanf("%d", &v) == 1) {
        printf("OK\n");
    } else {
        printf("Not an integer.\n");
    }
    return 0;
}

But it is suggest that you use fgets and strtol instead.

like image 93
Mark Byers Avatar answered Oct 23 '22 05:10

Mark Byers