Home > database >  What exactly happens when I use "scanf"?
What exactly happens when I use "scanf"?

Time:11-27

I'm trying to understand what happens when I'm using the "scanf" function, or to be more specific, what happen when I'm trying to enter letter into int with "scanf".

So I understood that when I'm trying to input letter into int, it's just doesn't work, so i wrote this to check what happends:

#include <stdio.h>

int main()
{
    int num=0;
    char term='a';
    scanf("%d%c", &num, &term);
    printf("%d%c", num, term);
 
    return 0;
}
 

When my input is "b" for example, the output is "0a", while I excepted it to be "0b" becouse the "scanf" would not entered "b" into num, and then he would entered it into "term".

Does someone know why its happens? I looked for answer and saw that its connect with the buffer but still I didn't understand what's happened.

CodePudding user response:

If you input a non-digit character when a digit is expected (like for the %d format) then scanf will fail immediately.

Similarly for other formats and mismatching inputs, as soon as invalid input is detected the function will fail and return.

You should always check what scanf returns.

When scanf fails, it will leave the input in the buffer. So next time you read you will get that data.

  •  Tags:  
  • c
  • Related