Nick5227 Nick5227 - 2 months ago 8
C++ Question

Confused on an If-else statement in C++

working on a project for class and all of the code works except for one portion that I think I may have messed up the whole code and may need to be re-written (which is why I'm asking here). The program asks you to pick one of three choices and then you pick how many of that item you'd like. However, we are supposed to display an error message if the user picks something not on the menu. Is it still possible to get a working else statement into my code?

cout << "Would you like a sandwich, a platter, or a salad? ";
cin >> choice;
if (choice == "sandwich")
{
cout << "\n How many sandwiches would you like? ";
cin >> sandwich;
if (sandwich >= 3)
{
cout << "\n Each sandwich costs: $" << SANDWICH_DISCOUNT << endl;
total = SANDWICH_DISCOUNT * sandwich;
cout << "\n The total cost of the sandwich(es) is: $" << total << endl<< endl;
}
else
{
cout << "\n Each sandwich costs: $" << SANDWICH << endl;
total = SANDWICH * sandwich;
cout << "\n The total cost of the sandwich(es) is: $" << total << endl<<endl;
}
}

if (choice == "platter")
{
cout << "\n How many platters would you like? ";
cin >> platter;
if (platter >= 3)
{
cout << "\n Each platter costs $" << PLATTER_DISCOUNT << endl;
total = PLATTER_DISCOUNT * platter;
cout << "\n The total cost of the platter(s) is: $" << total << endl<<endl;
}
else
{
cout << "\n Each platter costs $" << PLATTER << endl;
total = PLATTER * platter;
cout << "\n The total cost of the platter(s) is: $" << total << endl<<endl;
}
}
if (choice == "salad")
{
cout << "\n How many salads would you like? ";
cin >> salad;
if (salad >= 3)
{
cout << "\n Each salad costs $" << SALAD_DISCOUNT << endl;
total = SALAD_DISCOUNT * salad;
cout << "\n The total cost of the salad(s) is: $" << total << endl<<endl;
}
else
{
cout << "\n Each salad costs $" << SALAD << endl;
total = SALAD * salad;
cout << "\n The total cost of the salad(s) is: $" << total << endl<<endl;
}
}

Answer

You just need to add an else after each of your principal ifs, like:

if (choice == "sandwich")
{
....
} else if (choice == "platter")
{
...
} else if (choice == "salad")
{
...
} else {
cout << "\n     Option unavailable, try again." << endl;
}