shuramaan
shuramaan

Reputation: 161

C switch case default always executes

while ((c = getchar()) != '4') {
    switch (c) {
        case '1':
            printf("You pressed 1");
            break;
        case '2':
            printf("You pressed 2");
            break;
        case '3':
            printf("You pressed 3");
            break;
        case '4':
            break;
        default:
            printf("%c Wrong input, try again\n", c);
            printMenu();
    }
}
return 0;

}

ok, so i don't understand why default always executes. when i press either 1-3 it prints the massage in that case and right after it goes to execute the default case. what's wrong with the code?

Upvotes: 4

Views: 13256

Answers (5)

Darshan b
Darshan b

Reputation: 157

When you are reading a character using scanf - you will input y and press the whitespace character. y will be assigned to option (i.e. option - Y) and the whitespace character will be in buffer. when you call scanf next time present in the buffer, the whitespace character will be assigned to option hence goes to the default case. to avoid this leave a space before %c in scanf. this does not happen in case of integers or float.

Use the code below to get expected results :

while ((c = getchar()) != '4') {
    getchar();
    switch (c) {
        case '1':
            printf("You pressed 1\n");
            break;
        case '2':
            printf("You pressed 2\n");
            break;
        case '3':
            printf("You pressed 3\n");
            break;
        case '4':
            break;
        default:
            printf("%c Wrong input, try again\n", c);
            //printMenu();
    }

Upvotes: 3

Arun
Arun

Reputation: 20393

From the manpage:

   fgetc(), getc() and getchar() return the character read as an
   unsigned char cast to an int or EOF on end of file or error.

I would try to print the character, both as a char and as an int, to see what's going on.

  while ((c = getchar()) != '4') {
+     printf( "c = %c (%d)\n", (char) c, c );
      switch (c) {

Generally, that is sufficient to understand and fix the problem :-)

Upvotes: 2

nneonneo
nneonneo

Reputation: 179552

If you are typing in characters at the console, then you are probably pressing Enter after your entry. This will appear in getchar as a \n character, which doesn't appear in any of your switch cases.

You can simply choose to add case '\n': break; to ignore this case.

Upvotes: 11

dohashi
dohashi

Reputation: 1841

I believe the problem is that those breaks don't break the while loop, only the switch. You are probably entering 1 and enter and so the newline is read as a second character from getchar.

Upvotes: 1

srsci
srsci

Reputation: 239

Add a break to default. Thats where the problem is.

Upvotes: -6

Related Questions