简体   繁体   English

C:switch语句中的退出情况

[英]C:exit case in switch statement

i just have a quick question regarding the switch case. 我只是对开关盒有一个简单的问题。 can I do this? 我可以这样做吗? I can't get it to work. 我无法正常工作。 the program just says invalid 3 times when i type quit. 当我键入退出时,该程序仅说无效3次。 excuse the pseudo code. 请原谅伪代码。 oops i forgot to mention that the printf function looks like this before that part. 哎呀,我忘了提到那一部分之前,printf函数看起来像这样。

char choice;
printf("list, add, delete, write, quit\n");

do
{
scanf("%c", &choice);
//if (&choice== "quit"){exit(1);}

switch(choice)
    {
        case "list":
        case "add":
        case "delete":
        case "write":
        default:
            printf("Invalid\n");
            break;
        case "quit":
        exit (1);

    }while(&choice !="quit");

} }

You can't compare strings like that. 您不能比较这样的字符串。 String comparison should be done with strcmp and its kin. 字符串比较应使用strcmp及其同类进行。 In this case, you're comparing the addresses of the strings. 在这种情况下,您要比较字符串的地址。

although you can't compare strings directly the way you want, there's a way you can use dictionaries and defines/enums to engage a switch (see what I did there): 尽管您无法以所需的方式直接比较字符串,但是有一种方法可以使用字典和定义/枚举进行切换(请参阅我在此处所做的事情):

enum choices { LIST, ADD, DELETE, WRITE, QUIT, INVALID };

int
getchoice(char *input)
{
    static struct choices {
        enum choices val;
        const char *string;
    } choices [] = {
        { LIST, "list" },
        { ADD, "add" },
        { DELETE, "delete" },
        { WRITE, "write" },
        { QUIT, "quit" },
        { -1, NULL }
    };
    int i;

    for (i = 0; choices[i].val != -1; i++)
        if (strcmp(input, choices[i].string) == 0)
            break;
    if (choices[i].val == -1)
        return INVALID;
    return (choices[i].val);
}

and then for your switch statement: 然后为您的switch语句:

switch (getchoice(choice)) {
case LIST:
case ADD:
case WRITE:
case DELETE:
case INVALID:
default:
    printf("Invalid\n");
    break;
case QUIT:
    exit(1);
}

caveat emptor, as this hasn't been run through a compiler, but the general idea should be clear enough to adapt to your specific case(s). 请注意,因为尚未通过编译器运行,但总体思路应足够清楚,以适应您的特定情况。

另外,由于您在default情况下不使用break ,因此您将自动“跳入”默认情况(即使您输入的choice与“ list”,“ add”,“ delete”和“ write”相匹配) )

To answer your question: 要回答您的问题:

yes, you can call exit() anywhere, including inside a switch-case statement. 是的,您可以在任何地方调用exit() ,包括在switch-case语句内部。

But that code has many issues, see my comment at the question itself. 但是该代码存在许多问题,请参阅我对问题本身的评论。

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

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