eveo - 1 year ago 90
C Question

# Switch statement with strings?

I'm working on a small homework assignment and I'm supposed to make a food menu. Anyways, my switch isn't working. I'm trying to use a simple function that I can pass a value of "fish", "drink", or "chips" to and then it will output:

``````"Are you ordering FISH?" (or chips/drink)
``````

I can't get the switch to work, it's supposed to detect what I pass into it and then output a printf based on the switch case.

CODE:

``````#include <stdio.h>

printf("\nWelcome to Sunny FISH & CHIPS!\n\n");
printf("########     Fish :     Haddock(K) Large(L) | \$5.00\n");
printf("# FOOD #                Halibut(T) Large(L) | \$4.00\n");
printf("########     Chips:     Cut(C)     Large(L) | \$2.00\n");
printf("                        Ring(R)    Large(L) | \$3.00\n");
printf("                                            | \n");
printf("##########   Soft Drinks(S)        Large(L) | \$2.00\n");
printf("# DRINKS #   Coffee(C)             Large(L) | \$1.75\n");
printf("##########   Tea(T)                Large(L) | \$1.50\n");
printf("---------------------------------------------\n");
printf("Note: Medium price: 80%% of large.\n");
printf("       Small price: 60%% of large.\n");
printf("TAX is 10%%.\n");
printf("More than 5 fish, 10%% discount on drink.\n");
printf("Every 10 fish purchased, get 1 free softdrink.\n");
printf("  - size of drink is according to size of fish\n");
}

void question (char choice[5]) {
switch (choice[5])
{
case choice["fish"]:
printf("Do you order FISH?\n");
case choice["drink"]:
printf("Do you order CHIPS?\n");
case choice["chips"] :
printf("Do you order DRINKS?\n");
default :
printf("Enter a valid choice: \n");
}
}

main() {

question("fish");

}
``````

In addition to the other answers, if you find that your list of choices all begin with a unique letter (or have a unique letter in another position) then you can `switch` on that letter:

``````switch (choice[0]) {
case 'f':
// they chose fish
break;
case 'c':
// they chose chips
break;
case 'd':
// they chose drink
}
``````

This will be faster than using `strcmp` (although it doesn't matter for your case) and is less maintainable. However, it's good to know all the options and realise how you can use some of these things.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download