+ 1
I need some help in C++
What's wrong with this code? #include <iostream> using namespace std; int main() { int choice; cin >> choice; /* Типы кофе: 1. Espresso 2. Americano 3. Cappuccino 4. Latte */ switch(choice) { case 1: cout << " Espresso"; break; case 2: cout << " Americano"; break; case 3: cout << " Cappuccino"; break; case 4: cout << " Latte" break; } }
4 Answers
+ 4
cout << " Latte";
With this change, the code will compile and run without error.
Also it would be good to have a default case to handle unexpected input from the user.
switch(choice) {
case 1:
cout << " Espresso";
break;
case 2:
cout << " Americano";
break;
case 3:
cout << " Cappuccino";
break;
case 4:
cout << " Latte";
break;
default:
cout << "Invalid choice";
}
In this way you can handle situations when a user inputs an unexpected value, it will print "Invalid choice"
+ 5
After "Latte" you forgot a semicolon ";"
+ 1
Your input is text and not numbers, you need to use string instead of int.
An if else if can help convert the string answer into numbers to run the switch statement.
#include <iostream>
using namespace std;
int main()
{
string choice;
int result = 0;
cin >> choice;
if (choice == "Espresso" ||
choice == "espresso")
{
result = 1;
}
else if (choice == "Americano" || choice == "americano")
{
result = 2;
}
else if (choice == "Cappuccino" ||
choice == "cappuccino")
{
result = 3;
}
else if (choice == "Latte" ||
choice == "latte")
{
result = 4;
}
else
{cout << "try again";}
/* Типы кофе:
1. Espresso
2. Americano
3. Cappuccino
4. Latte
*/
switch(result)
{
case 1:
cout << " Espresso";
break;
case 2:
cout << " Americano";
break;
case 3:
cout << " Cappuccino";
break;
case 4:
cout << " Latte";
break;
}
}