Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C program. Switch case/user input. default keeps executing

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

My outputs:

My Outputs

Correct 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;
}
like image 285
J.Godinez Avatar asked May 31 '26 14:05

J.Godinez


2 Answers

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
like image 52
kocica Avatar answered Jun 02 '26 07:06

kocica


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).

like image 22
hnefatl Avatar answered Jun 02 '26 06:06

hnefatl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!