jonnyboy1555 jonnyboy1555 - 11 months ago 51
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)");
scanf("%c", &ch);

switch (ch) {
case 'a':
printf("a. another: ");
case 'b':
printf("b. another: ");
case 'c':
printf("c: another ");
case 'd':
printf("d. another: ");
case 'e':
printf("e. another: ");
case 'f':
printf("f. Goodbye. ");
printf("That wasn't a through f. ");
} 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 Source

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':