-1

The program continues only if the user presses "Enter" in two cases. But my program doesn't wait for the user to press "Enter" at all and moves on to the next line of the code.

  int T1 ,T2;
  char c1,c2;
  printf("Enter Temperature T1: ");
  scanf("%d",&T1);
  printf("Enter Temperature T2: ");
  scanf("%d",&T2);
  printf("Press Enter after setting temperature T1\n");
  scanf("%c",&c1);
  while(c1 != '\n' && c1 != EOF);
  printf("Press Enter after setting temperature T2\n");
  scanf("%c",&c2);
  while(c2 != '\n' && c2 != EOF);
Weather Vane
  • 33,872
  • 7
  • 36
  • 56
rdx1994
  • 7
  • 2
  • use fgets to read from keyboard, atoi to convert with. scanf stores ENTER also in the buffer (stdin), the buffer is shared between calls to scanf – AndersK Dec 05 '16 at 11:42
  • 1
    Because the Enter keys you pressed after the numbers are put into the input buffer as newlines, which the `"%c"` formats will read. – Some programmer dude Dec 05 '16 at 11:42
  • 2
    `scanf("%c",&c1);` -> `scanf(" %c",&c1);` (notice the space) – artm Dec 05 '16 at 11:43
  • 1
    Please look at `while(c1 != '\n' && c1 != EOF);` too as these loops will hang (nothing changes). – Weather Vane Dec 05 '16 at 11:46
  • 4
    Please do not correct the posted code - it makes the question pointless. – Weather Vane Dec 05 '16 at 11:47
  • Sorry,my original code is this one. I made quite typos in initial question. This one doesn't work either. – rdx1994 Dec 05 '16 at 11:55
  • Also, fgets isn't working too. Can you please tell me how to go about it? Thank You. – rdx1994 Dec 05 '16 at 12:00
  • Possible duplicate of [Why doesn't getchar() wait for me to press enter after scanf()?](http://stackoverflow.com/questions/1391548/why-doesnt-getchar-wait-for-me-to-press-enter-after-scanf) – anatolyg Dec 05 '16 at 12:16

1 Answers1

1

Firstly, make one space before %c (scanf(" %c",&c1);) because format without the blank reads the next character, even if it is white space, whereas the one with the blank skips white space (including newlines) and reads the next character that is not white space.

Second, the while loop very next after the scanf which I have mentioned above will hang your code, so make it commented if you want to execute second printf statement.

aeb-dev
  • 313
  • 5
  • 16