c - Why does my switch statement print a case and default? -
#include <stdio.h> int main(void) { char ch; int end=0; printf("\npick letter through f. (f ends program)"); { scanf("%c", &ch); switch (ch) { case 'a': printf("a. another: "); break; case 'b': printf("b. another: "); break; case 'c': printf("c: "); 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 through f. "); break; } } while (end == 0); return 0; }
so if enter say:
a. another: wasn't through f.
if enter g say:
that wasn't through f. wasn't through f.
if enter f expected
f. goodbye.
and program terminates.
any tips on how fix this? i've tried looking while , answers not in c or you're forgetting break; statement. i'm new c, maybe it's obvious i'm not noticing, thought might due while loop? time
scanf("%c", &ch)
reads 1 character @ time. if you're typing letter , hitting enter, you're providing 2 characters: letter, , newline character (u+000a, '\n'
).
if want ignore newline characters, 1 option explicitly check them:
case '\n': break;
Comments
Post a Comment