I read input from the keyboard using scanf() in a while loop and print back on the screen using printf():
#include <stdio.h>
#include <conio.h>
int main(void)
{
char ch;
printf("enter your name");
while(ch!='/n')
{
scanf("%c",&ch);
printf("%c",ch);
}
getch();
return 0;
}
I want to know how printf() prints the value on screen, because when the user presses the enter key, the program is out of the loop.
It is not a good idea to check the value of
ch(inwhileloop) before assigning it a value.First before entering loop, it checks whether
chequals"\n"which it does not (hopefully).It enters the loop.
scanf()executes, waits for input. Suppose, you enter"a"and then press ENTER.As a whitespace character is encountered, it continues to next line, which prints the character entered earlier.
ch==a, so it enters the loop again.Now,
scanf()is executed again, the input buffer already has"\n", it is read."\n"read earlier, gets printed.ch == "\n", so the loop exits.The catch was that even though your read
"a"from the input, the input buffer already had"\n"the second time the loop was executed. To avoid situations like that you should use