Through my search for a solution I found this question. Which made me think and make some experiments:
Case 1
#include<stdio.h>
main()
{ char a;
//some code
scanf("%c",&a);
/*This code might not be evaluated(missed)
sometimes*/
//This is how it is solved
scanf(" %c",&a);
//the rest of code
}
case 2
#include<stdio.h>
main()
{ int a;
//some code
scanf(" %d ",&a);
//this one will take 2 numbers instead of one
//the rest of code
}
I don't know much about c language so it would be appreciated if someone explains these results to me.(I'm using turbo c++ if it matters.)
A couple of general notes:
scanf()
for example.So in your first case the example would be:
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:
you would see:
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:
Will tell the scanf that any white space characters (including the newline
'\n'
) left onstdin
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 howscanf
works: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:
could be satisfied by this input:
First the "%d" matches the 5, then the newline following the f matches the " "