简体   繁体   中英

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. excuse the pseudo code. oops i forgot to mention that the printf function looks like this before that part.

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. 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 (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.

But that code has many issues, see my comment at the question itself.

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