Alex Alex - 1 month ago 18
C Question

switch case inside loop

i've run into a slight problem with my function. When i typed in 8 i want it to quit. However when i type 8, it prints out my default message then quits. What have i missed?

void Selection()
{
int selection;

while (selection != 8)
{
printMenu();
scanf("%d", &selection);
switch (selection)
{
case '1': /*FUNCTION HERE*/ ; break;
case '2': /*FUNCTION HERE*/ ; break;
case '3': /*FUNCTION HERE*/ ; break;
case '4': /*FUNCTION HERE*/ ; break;
case '5': /*FUNCTION HERE*/ ; break;
case '6': /*FUNCTION HERE*/ ; break;
case '7': /*FUNCTION HERE*/ ; break;
case '8': break;
default: printf("Unkown command please try again.\n"); break;
}
}
}

Answer

The line

scanf("%d", &selection);

inputs an int value, say 8. But in your case statement

case '8': break;

you are testing a character value. Please change all those case statements to such as

case 8: break;

Also, you must initialise the local variable selection before you first test it. Compiler should have warned you about that.

Comments