Hello, I am creating a cola machine program which's goal is to display the different types of beverages and have the user input the beverage of his/her choice, and display their choice. If a user inputs a number that does not define any beverages then the message, "Error. The choice was not valid, here is your money back." must be displayed.
I have accomplished this with switch statement with ease but having trouble accomplishing it with if/else statements. Kindly review my code and suggest what I need to do in order to accomplish my goal. This is an assignment.
The problem is that when I input 1 in the console it displays my choice, "coke" but when I enter any other beverage number it displays the message from else statement. And no it's not about the breakpoints, have tried that already. By the way I am using Code::Blocks, GNU GCC compiler, just in case things work slightly differently in othe c++ apps.
#include <iostream>
usingnamespace std;
int main()
{
int beverages;
cout << "You have 5 choices of beverages; 1. Coke, 2. Water, 3. Pepsi,
4. Crush, 5. Pakola. Enter a number to choose a beverage of your choice."
<<endl;
cin >> beverages;
if (beverages == 1) {
cout << "Coke";
if (beverages == 2) {
cout << "Water";
}
if (beverages == 3) {
cout << "Pepsi";
}
if (beverages == 4) {
cout << "Crush";
}
if (beverages == 5) {
cout << "Pakola";
}
}
else {
cout << "Error. The choice was not valid, here is your money back.";
}
return 0;
}
int main()
{
int beverages;
cout << "You have 5 choices of beverages; 1. Coke, 2. Water, 3. Pepsi,
4. Crush, 5. Pakola. Enter a number to choose a beverage of your choice."
<<endl;
cin >> beverages;
if (beverages == 1) {
cout << "Coke"; // You put the braces on the bottom, which tells the program
// if beverage ==1 also do the things inside the if condition
if (beverages == 2) {
cout << "Water";
}
if (beverages == 3) {
cout << "Pepsi";
}
if (beverages == 4) {
cout << "Crush";
}
if (beverages == 5) {
cout << "Pakola";
}
}
Side note: if there's only one line after the conditions, you don't need curly brackets. So you can do something like:
if else-if else is an adequate control structure, especially if you have to use it as a problem requirement, as often happens, but a better structure is a switch control.
@FurryGuy, @kemort and @McLemore thanks a lot it worked out using else if statement for beverages 2-5.
And thanks a lot to everyone else who tried to help me. You all are the best. :)