Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 830
shuramaan Avatar asked Sep 15 '25 05:09

shuramaan


2 Answers

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.

like image 200
nneonneo Avatar answered Sep 17 '25 18:09

nneonneo


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();
    }
like image 45
Darshan b Avatar answered Sep 17 '25 20:09

Darshan b