Let’s say that I use scanf to, for example, read a character from the keyboard. After that I use printf to print the character I just read.
scanf("%c",&ch);
printf("%c",ch);
When scanf is reading the character, I must press enter to continue and run the printf, right?
And let’s say I enter ABCD with the keyboard. After that printf will print A.
But when I do this:
do {
scanf("%c",&ch);
printf("%c",ch);
} while (ch!='\n');
and enter ABCD with the keyboard, I assume that the printf must print A. And because A is not \n it will continue the loop, right?
But instead of this it will print ABCD. Why does this happen?
When you type in
"ABCD\n", eachscanf("%c",&ch);reads onecharfrom the input buffer, until the newline is reached.So after the
'A'is printed, there is still a"BCD\n"in the buffer, so that the nextscanfimmediately succeeds reading anotherchar,'B'in the next iteration of the loop.