J.Godinez
J.Godinez

Reputation: 49

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;
}

Upvotes: 3

Views: 1340

Answers (4)

Ankur Agrawal
Ankur Agrawal

Reputation: 48

The scanf("%c", &ch); statement requires you to hit the enter key. This inserts the newline \n character in the input stream. During the iteration when the \n character is read from the input stream, the default switch-case gets executed.

Since only a single character is being read, you can consider using getchar to avoid this. Alternatively, you can enter the string in a single line followed by enter key, e.g. : +++---***+ or you can add another switch case to handle the newline character.

Upvotes: 0

kocica
kocica

Reputation: 6465

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

Upvotes: 5

IP002
IP002

Reputation: 547

You must use scanf(" %c", &ch); to eliminate all the whitespace, when using %s tough you dont need the space.

Upvotes: 0

hnefatl
hnefatl

Reputation: 6037

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

Upvotes: 2

Related Questions