-1

Case 1:

printf("Enter the operation you want to carry out (+, -, /, *): ");
scanf("%c", &operator);

printf("Enter two numbers: ");
scanf("%lf %lf", &num_1, &num_2);

In this case, the program was executed smoothly.

Case 2:

printf("Enter two numbers: ");
scanf("%lf %lf", &num_1, &num_2);

printf("Enter the operation you want to carry out (+, -, /, *): ");
scanf("%c", &operator);

In this case, after I entered the numbers, it directly executed the rest of the program and the default error message was printed.

Barmar
  • 741,623
  • 53
  • 500
  • 612

1 Answers1

1

Because, per the man page:

Most conversions discard initial white space characters (the exceptions are noted below)

one of those exceptions being %c.

The newline you input when you hit "enter" in your terminal is a character. When the program is waiting for a %lf it just discards that, but for %c it is used as the accepted input.

Ideally, you wouldn't need to hit "enter" at all, but many (most?) terminals are line-buffered by default, so nothing gets sent to your program until you do. For a more flexible UI, use something like curses or a proper graphical interface.

Asteroids With Wings
  • 17,071
  • 2
  • 21
  • 35