tags:

views:

797

answers:

2

How can I check if an integer initialized from function scanf is a number?

...in the simpler way possible

thanks :)

+4  A: 

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.

Mark Byers
Thanks man, it works but if I put this in a loop, doesn't work properly, if the input is a string at the begin, the loop is infinite, I can resolve?
I put a getchar(); inside... works now
`sscanf` and `scanf` is a bad idea. Both produce undefined behavior on overflow.
AndreyT
Good point. strtol is better, but he did ask how to use scanf, so I still think we ought to tell him the answer to his question, even if we are advising him not to use this method.
Mark Byers
John Bode
OK, I updated the post to make it clear!
Mark Byers
+3  A: 

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.

AndreyT