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
  • 349,597
  • 67
  • 533
  • 578
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
  • 80,138
  • 16
  • 128
  • 173
2

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

Archmede
  • 1,592
  • 2
  • 20
  • 37
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
  • 780
  • 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
  • 819
  • 2
  • 11
  • 25