1

I have been tasked to create a simple lower to upper case program. However, while testing if my input prints correctly, I have noticed that every time I enter a character, it always loops again even when its not supposed to.

#include <stdio.h>

int main() {
  char input;

  //enter a character
  //set the given input char to variable
  printf("Enter a character in lower case: \n");
  input = getchar();

  //Sentinel value is Q
  while (input != 'Q'){
    printf("you entered %c.\n",input);
    printf("\n");

    printf("Enter a character in lower case: \n");
    input = getchar();  //gets input from inside the loop
  }
  printf("Goodbye \n");
  return 0;
}

test output (I input the character 'g' and pressed enter once):

Enter a character in lower case:
g
you entered g.

Enter a character in lower case:
you entered
.

I'm not seeing the problem.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Bob Gonr
  • 41
  • 1
  • 8
  • 1
    Have you tried entering `Q` and seeing what happens? – Andrew Morton Jan 11 '16 at 20:41
  • 1
    It's printing the `'\n'` (newline) character. – Fiddling Bits Jan 11 '16 at 20:41
  • There are many dups of this which you may find relevant: 1) http://stackoverflow.com/questions/2549701/using-getchar-in-a-while-loop 2) http://stackoverflow.com/questions/19342434/why-does-getchar-in-while-not-execute-after-first-iteration?answertab=oldest#tab-top – P.P Jan 11 '16 at 20:45

1 Answers1

6

The problem here is caused by the newline character entred into the stdin by pressing the ENTER key. Before proceeding for the next input, you need to clear the input buffer , like adding

 while (getchar() != '\n');

before asking for the next input.

That said, getchar() returns an int. A char may not be enough to hold the return value always, Change

 char input;

to

int input = 0;
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261