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;
}
you need to change
scanf("%c", &operator);
to
scanf("%s", &operator);
it will run.