0

Why the error does not occur when I put a float number?

int m;
if(scanf("%d%",&m)!=1)
{
    printf("Error\n");
    exit(1);
}
2
  • 1
    Depends on exactly how the "float" is given: For example, "1.2" can be (correctly) seen as an integer input (i.e. "1" - ignoring the rest); however, ".123" will most likely fail. Commented Mar 6, 2020 at 13:14
  • Maybe this post: C-Checking if input (float) is purely integer or float will be helpful? Commented Mar 6, 2020 at 13:16

1 Answer 1

2

Because %d will consume all decimal digits until the first non-decimal digit. So if you enter "50.5" m will have the value 50 and the characters ".5" will remain in the buffer unread.

There are many possible solutions. Here's one:

int m ;
double fm ;

if( scanf("%f%",&fm) != 1 || 
    modf( fm, &m) != 0 )
{
    printf("Error\n");
    exit(1);
}
Sign up to request clarification or add additional context in comments.

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.