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.