Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
822 views
in Technique[技术] by (71.8m points)

c - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
");
    } else {
        printf("Not an integer.
");
    }
    return 0;
}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...