user1813332
user1813332

Reputation: 55

Abnormal behaviour of scanf

I'm using GCC complier. In my program I have used 3 scanfs, but while executing it only performs 2 scanfs. Why is it skipping 1 scanf? It's only executing the else condition.

#include <stdio.h>
int main()
{
    int h, c, t;
    printf("tensile");
    scanf("%d", &h);
    printf("tensile1");
    scanf("%d", &c);
    printf("tensile2");
    scanf("%d", &t);
    if( h > 50 && c > 0.7 && t > 5600)
        printf("HI");
    else
        printf("bye");
    return 0;
}

Upvotes: 0

Views: 180

Answers (2)

Keith Thompson
Keith Thompson

Reputation: 263577

You defined c as an int and compared it to 0.7. Even ignoring any scanf issues, that doesn't make much sense. Decide for each of your variables whether it should hold only whole numbers or (possibly fractional) real numbers. For whole numbers, you probably want int. For real numbers, you probably want double. And then you need to use the proper format for scanf, depending on the type of the variable. Read your scanf documentation for details.

With the "%d" format, scanf will read a single integer (after skipping any whitespace, including newlines), and then stop. If the input is "12.34", it will read the "12", store 12 in the variable, and leave the ".34" in the input stream. Later calls to scanf with "%d" will fail when they see the '.' character. Use one of the floating-point formats to read a variable of type double and permit inputs like "12.34".

scanf returns a result indicating how many items it successfully read, or an error indication. You should test that result so your program will detect errors rather than blindly continuing to run with bad data.

Showing us exactly (i.e., copy-and-paste) the input you gave to your program would have made it easier to answer your question.

Printing the values of your variables and the result returned by scanf would have helped you understand what's going on -- or you can examine the values in a debugger if one is available.

Some things to watch out for: scanf will report failure on input syntax errors (e.g., if it's looking for a real number and you enter "foobar"), but it won't necessarily diagnose overflows. If you enter 1.0e99999999 for a floating-point input, the behavior is undefined. The only real way to avoid that problem is to avoid using scanf for numeric input. (IMHO this is a flaw in the way the C standard defines the *scanf functions.)

Floating-point comparisons are notoriously unreliable. If c is a floating-point variable, c > 0.7 could be either true or false, since the value 0.7 cannot be represented exactly in binary floating-point.

Upvotes: 2

Anirudha Agashe
Anirudha Agashe

Reputation: 3530

Change the data type of variable c to float and use %f as format specifier. It is skipping because you are providing float value to an integer variable

Upvotes: 1

Related Questions