amulous
amulous

Reputation: 732

Validating Integer Input

int a;
scanf("%d",&a);

How can I ensure the code doesn't work if a non-digit character is given as input to the scanf() statement? [I need a solution that doesn't make me change the data type to char]

Upvotes: 1

Views: 99

Answers (3)

Ankur
Ankur

Reputation: 126

You can use a do while loop for validating input from user like:

int read,a;
do {
        read = scanf("%c", &a);
    }while(read != EOF && a != '\n'); //change validation here according to condition

Upvotes: 0

John3136
John3136

Reputation: 29266

The scanf return code will tell you how many items in your arg list were filled. This may still not be what you want: I think you'll find input "123four" will still return 1, with a=123.

Upvotes: 2

icktoofay
icktoofay

Reputation: 128991

If the first character is not a digit, then %d will fail to match, and a will not be assigned. The return value of scanf tells you how many items were assigned. If it's one, then clearly it was at least partially a valid number. If it's zero, that means it couldn't be parsed as a number, and you may want to signal an error.

Upvotes: 2

Related Questions