After the initial iteration, the printf()
output is shown twice each iteration. Why?
int main()
{
int ch;
for( ch = ' '; ch != 'q'; ) {
printf("Enter a character: ");
ch = getchar();
}
printf("You entered a q!\n");
return 0;
}
The terminal output is:
Enter a character: w
Enter a character: Enter a character: a
Enter a character: Enter a character: q
You entered a q!
As everyone has already stated, getchar()
is consuming a newline ('\n') making you have two iterations. A way to fix this is to do this:
int main(){
int ch;
for( ch = ' '; ch != 'q'; ) {
printf("Enter a character: ");
ch = getchar();
getchar();
}
printf("You entered a q!\n");
return 0;
}
The reason for the second getchar()
is to consume that newline so you won't have a double output of the same thing. Using this method will only work if you are only inputting one character.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments