0

In this program , getchar is apparently needed to continue the while(1) loop. If I remove getchar(), the program terminates after printing the sum of the two numbers.

  while (1) {
    printf("Input two integers\n");
    scanf("%d%d", &a, &b);
    getchar();

    c = a + b;

    printf("(%d) + (%d) = (%d)\n", a, b, c);

    printf("Do you wish to add more numbers (y/n)\n");
    scanf("%c", &ch);

    if (ch == 'y' || ch == 'Y')
      continue;
    else
        break;
  }
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
  • 2
    Step through in a debugger to see why. – tadman Aug 16 '19 at 23:04
  • Check the return value from `scanf` to make sure it read something, and print that result. It's hitting the break. This should help explain the issue: https://stackoverflow.com/questions/1669821/scanf-skips-every-other-while-loop-in-c – Retired Ninja Aug 16 '19 at 23:04

1 Answers1

1

You have junk in the input buffer from the scanf() before the getchar(). In particular, the newline.

It's usually far easier to just up and rewrite everything to use fgetc(), but in this case you can make a lot of improvement by doing something like this:

do{
   scanf("%c", &ch);
   if (ch == '\n')
       printf("Do you wish to add more numbers (y/n)\n");
} while (ch != 'y' && ch != 'Y' && ch != 'n' && ch != 'N');

if (ch == 'y' || ch == 'Y')
  continue;
else
    break;
Joshua
  • 40,822
  • 8
  • 72
  • 132