0

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!
John Kugelman
  • 330,190
  • 66
  • 504
  • 555
rj1094
  • 11
  • 2

4 Answers4

4

You didn't enter w on the command line. You entered w\n. That's two characters.

Bill Lynch
  • 76,897
  • 15
  • 123
  • 168
2

Because getchar reads a character and '\n', not only the character that you typed.

Archmede
  • 1,302
  • 1
  • 16
  • 32
Riccardo Bonafede
  • 610
  • 1
  • 9
  • 17
0

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.

Manav Dubey
  • 758
  • 11
  • 26
0

As comments and previous answers have stated, getchar() does not read the newline at the end. The quick fix is to add another getchar(); at the end of your loop like this:

int main()
{
  int ch;
  for( ch = ' '; ch != 'q'; ) {
     printf("Enter a character: ");
     ch = getchar();
     getchar();
  }
  printf("You entered a q!\n");

  return 0;
}

If you want a more flexible solution that will work if the user types more than one character, try this:

int main()
{
  int ch;
  for( ch = ' '; ch != 'q'; ) {
     printf("Enter a character: ");
     ch = getfirstchar();
  }
  printf("You entered a q!\n");

  return 0;
}
int getfirstchar() {
  int c = getchar();
  while(getchar() != '\n')
    ;
  return c;
}

I moved reading the character into a separate function so it's more adaptable to future code.

anonymoose
  • 768
  • 2
  • 10
  • 24