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.