0

I am currently learning c, and this is the code I am running. I am asking the user for input, and the only valid inputs are 0,1,2. 0 allows the user to quit the program. When I run this program and call the functions function1 and function2, the output I get after looping is:

enter image description here

#include<stdio.h>
int function2(int num3, char ch);
int function1(int num1, int num2, char ch);

int main()
{
  int number, num1, num2, num3;
  char ch;
  do  {
       printf("Enter 0 (quit), 1, 2:");
       scanf("%d", &number);
      if (number == 1)
        {
          printf("Enter character, first number, and second number: ");
          scanf("%c %d %d", &ch, &num1, &num2);
          function1(num1, num2, ch);
        }
      else if (number == 2)
        {
          printf("Enter character and another number: ");
          scanf("%c %d", &ch, &num3);
        }

      else
        {
          if (number == 0)
            {
              printf("Exit \n");
            }
          else
            {
              printf("Please reenter data. \n ");
            }
        }
    }
  while (number != 0);
  return 0;
}

int function1(int num1, int num2, char ch)
{
  printf("%d %c %d", num1, ch, num2);
}

int function2(int num1, char ch)
{
  printf("%d %c", num1, ch);

Is the problem how I am using printf and scanf? I tried using fflush(stdout) but it didn't change the outcome.

  • Put a `' '` space before `" %c..."` in all your *format strings*, e.g. `scanf(" %c %d %d", &ch, &num1, &num2)` Then spend the 45 minutes or so it takes to really read [man 3 scanf](http://man7.org/linux/man-pages/man3/scanf.3.html) -- it will save you 100's of hours of frustration later `:)` What happens is your `"%d"` leaves the `'\n'` in `stdin` unread -- so when then your `"%c"` reads the `'\n'` as it's input (`"%c"` does not ignore leading whitespace). Adding a `' '` before it fixes that issue. – David C. Rankin Jan 31 '20 at 04:25
  • 1
    Because `"%d"` **ignores** (skips, etc..) leading *whitespace* `:)` [man 3 scanf](http://man7.org/linux/man-pages/man3/scanf.3.html) really is your friend -- even though it might not look that way to begin with... – David C. Rankin Jan 31 '20 at 04:30

0 Answers0