I'm really confused about the usage of getchar()
and scanf()
. What's the difference between these two?
I know that scanf()
[and family] get a character by character from the user [or file] and save it into a variable, but does it do that immediately or after pressing something (Enter
)?
and I don't really understand this code, I saw many pieces of code using getchar()
and they all let you type whatever you want on the screen and no response happen, but when you press enter
it quits.
int j, ch;
printf("please enter a number : \n");
while (scanf("%i", &j) != 1) {
while((ch = getchar()) != '\n') ;
printf("enter an integer: ");
}
Here in this code can't I use scanf()
to get a character by character and test it? Also, what does this line mean?
scanf("%i", &j) != 1
because when I pressed 1 it doesn't differ when I pressed 2? what does this piece do?
and when this line is gonna happen?
printf("enter an integer: ");
because it never happens.
Well, scanf
is a versatile utility function which can read many types of data, based on the format string, while getchar()
only reads one character.
Basically,
char someCharacter = getchar();
is equivalent to
char someCharacter;
scanf("%c", &someCharacter);
I am not 100% sure, but if you only need to read one character, getchar()
might be 'cheaper' than scanf()
, as the overhead of processing the format string does not exist (this could count to something if you read many characters, like in a huge for loop).
For the second question.
This code:
scanf("%i", &j) != 1
means you want scanf
to read an integer in the variable 'j'. If read successfully, that is, the next input in the stream actually is an integer, scanf
will return 1, as it correctly read and assigned 1 integer.
See the oldest answer to this SO question for more details on scanf
return values.