1
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]

2
  • 1
    By reading the documentation for scanf and making use of the return value. Simple! Commented Jun 24, 2013 at 6:33
  • Thanks! The return value did the job. Commented Jun 24, 2013 at 6:40

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Finally understood this.
2

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.