Check if a value from scanf is a number?

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


Solution 1:

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.

Solution 2:

Your question is weirdly worded. An initialized integer is always a number (aside from exotic cases of trap representations), which means that there's no need to check anything.

I would guess that you need to check whether the given string is a valid representation of a number. For that, you first need to define what the valid representation should look like. Do you allow sign? Is a redundant + allowed (as a sign)? What about 0x prefix for hexadecimals? And so on.

C language offers its own set of rules that define the language's idea of a valid string representation of an integer. If that's what you need, then in order to verify whether the given string satisfies these rules, the best way is to use string-to-integer conversion function like strtol (and other functions from strto... group) and then check for the error condition.

Beware of the answers that suggest writing your own function that would verify these rules. This just doesn't make any sense, since the standard function exists already. Also, strictly speaking, in real-life programming there's rarely a need to perform verification without the actual conversion. strto... will do both.

Also, stay away from functions from scanf group to perfrom string-to-integer conversion. These functions produce undefined behavior on overflow (i.e. if the input string representation is too long). In general case, the only proper way to do such a conversion in C is functions from strto... group.