I started learning C and tried to code this math program using switch statements. The program runs and works just fine when I scan the operator first and then scan the numbers. But if I switch the order of the scanf functions to take the numbers first and then the operators, the program takes the number but after that it does not take the second input (the operator) and just prints the default value (invalid input). Why is this happening?
I have provided the code (if I run this code, the problem occurs with the program just taking the numbers and not taking the operators. But of the order is flipped, it works).
#include <stdio.h>
int main()
{
float a, b, result;
char operator;
printf("Enter 2 numbers:");
scanf("%f %f", &a, &b);
printf("Choose a math operator (+, -, *, /):");
scanf("%c", &operator);
switch (operator)
{
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
default:
printf("\nInvalid operator");
return -1;
}
printf("%f", result);
return 0;
}
The format string "%c" will read the newline character from the first line of input. What you want instead is " %c" which will skip leading whitespace, so replace the line
scanf("%c", &operator);
with
scanf(" %c", &operator);
See also https://pubs.opengroup.org/onlinepubs/9699919799/
A directive composed of one or more white-space characters shall be executed by reading input until no more valid input can be read, or up to the first byte which is not a white-space character, which remains unread.
you need to change
scanf("%c", &operator);
to
scanf("%s", &operator);
it will run.