user1428720
user1428720

Reputation: 1

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");

}

Upvotes: 0

Views: 21316

Answers (4)

tbert
tbert

Reputation: 2097

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

Upvotes: 2

Zmaster
Zmaster

Reputation: 1135

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.

Upvotes: 0

Levon
Levon

Reputation: 143022

Also, since you don't use break other than in the default case, you'll "drop" through to the default case automatically (even if your input choice matched "list", "add", "delete" and "write")

Upvotes: 1

Mahmoud Al-Qudsi
Mahmoud Al-Qudsi

Reputation: 29549

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.

Upvotes: 4

Related Questions