A couple of general notes:
- If you want to ask questions about C it would be beneficial for you to read about how the functions work. There is a lot of documentation available online for
scanf()
for example.
- It's always better when you can give full compile-able examples rather than //some code
So in your first case the example would be:
char a, b;
scanf("%c", &a);
scanf("%c", &b); // this one will be "missed"
The reason is that when you enter a character in to stdin
you're getting two characters really, what was typed plus an invisible newline character ('\n'
). So really the second scanf isn't "missed" it's just picking up a character that doesn't have an ASCII representation.
If you printed these with:
printf("%c %d\n%c%d\n", a, a, b, b);
you would see:
>> ./my_prog
>> a
>> a 97
10
Because you entered "a\n" and the two scanf's read first the "a" then the "\n" respectively.
Using a scanf with a space before it:
scanf(" %c", &b); // this one will work instead
Will tell the scanf that any white space characters (including the newline '\n'
) left on stdin
should be ignored.
In your second case, it's not looking for 2 numbers, it's looking for a number and a white space character. scanf(" %d ", &a)
says "ignore any white space, then look for a decimal number, then look for white space". However once the variable (a) is filled it stops reading, because this is how scanf
works:
A directive composed of one or more white-space characters shall be executed by reading input until no more valid input can be read, or up to the first byte which is not a white-space character, which remains unread.
So it's not really looking for another number, you can type anything at this point and it will be happy because it's just looking for another white space character to be input. So this:
scanf(" %d ", &a);
could be satisfied by this input:
>> 5
f
First the "%d" matches the 5, then the newline following the f matches the " "