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?
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With