jonnyboy1555 jonnyboy1555 - 22 days ago 4
C Question

Why does my switch statement print a case and default?

#include <stdio.h>

int main(void)
{
char ch;
int end=0;
printf("\nPick a letter a through f. (f ends the program)");
do
{
scanf("%c", &ch);

switch (ch) {
case 'a':
printf("a. another: ");
break;
case 'b':
printf("b. another: ");
break;
case 'c':
printf("c: another ");
break;
case 'd':
printf("d. another: ");
break;
case 'e':
printf("e. another: ");
break;
case 'f':
printf("f. Goodbye. ");
end=1;
break;
default:
printf("That wasn't a through f. ");
break;
}
} while (end == 0);
return 0;
}


So if you enter a then it will say:

a. another: That wasn't a through f.


If you enter say g then it will say:

That wasn't a through f. That wasn't a through f.


If you enter f then it will do as expected

f. Goodbye.


and the program terminates.

Any tips on how to fix this? I've tried looking it up for a while and I get answers not in C or they say you're forgetting a break; statement. I'm new to C, as well so maybe it's something obvious I'm not noticing, I also thought it might be due to something with the do while loop? Thanks for your time

Answer

scanf("%c", &ch) reads one character at a time. If you're typing a letter and then hitting Enter, then you're providing two characters: the letter, and a newline character (U+000A, '\n').

If you want to ignore newline characters, one option is to explicitly check for them:

case '\n':
    break;
Comments