简体   繁体   中英

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;
        }
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM