简体   繁体   English

开关盒内循环

[英]switch case inside loop

I've run into a slight problem with my function. 我的功能遇到了一个小问题。 When I typed in 8 I want it to quit. 当我输入8时,我希望它退出。 However when I type 8, it prints out my default message then quits. 但是,当我键入8时,它会打印出我的默认消息,然后退出。 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 . 输入一个int值,例如8 But in your case statement 但是在你的case

case '8': break;

you are testing a character value. 您正在测试一个字符值。 Please change all those case statements to such as 请将所有这些case陈述更改为

case 8: break;

Also, you must initialise the local variable selection before you first test it. 另外,您必须在首次测试之前初始化局部变量selection Compiler should have warned you about that. 编译器应该已经对此发出警告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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