Default statement is executed every time I enter the correct char input. What am I missing?
My outputs:

Correct outputs:

#include <stdio.h>
void main() {
char ch = '?';
float f;
double a = 10.00, b = 20.00;
int i;
for (i = 0; i < 10; i++) {
scanf("%c", &ch);
switch (ch) {
case '+':
f = a + b;
printf("f = %.0f\n", f);
break;
case '-':
f = a - b;
printf("f = %.0f\n", f);
break;
case '*':
f = a * b;
printf("f = %.0f\n", f);
break;
case '/':
f = a / b;
printf("f = %.2f\n", f);
break;
default:
printf("invalid operator\n");
}
}
return 0;
}
The scanf() function removes whitespace automatically before trying to parse things other than characters.
The character formats (%c, %[…], %n) are exception, they don't remove whitespace.
In your case, you have to skip leading white-spacing, to do that change
scanf("%c", &ch);
to
scanf(" %c", &ch);
^ Note the space
With scanf, after you hit a key you then need to hit "enter". This inserts two characters into the input stream - the one you pressed, and the newline character \n (and possibly \r, the carriage return character).
For demonstration, if you enter "a enter" then the input stream looks like
a\n
If you enter "a b c d enter", then the input stream looks like:
abcd\n
The first iteration of your loop will read the character you entered, the next will read the newline character (which isn't one of those in your cases so hits the default statement.
To read a single character without a newline, consider getchar, or just two extra cases that catche the newline character and the carriage return character and does nothing in either case (but bear in mind this will "steal" some useful iterations of your loop).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With