patterncppModerate
Cola Machine #1
Viewed 0 times
machinecolastackoverflow
Problem
I have been working on the code listed here.
I am working on Problem #2, 0 stars. Here's what I have to do:
Write a program that presents the user w/ a choice of your 5 favorite beverages (Coke, Water, Sprite, ... , Whatever).
Then allow the user to choose a beverage by entering a number 1-5.
Output which beverage they chose.
NOTE:
I won't be creating a switch statement or making a error message if you give a value other than one that is 1-5, because that are part of the next step in the project.
I am working on Problem #2, 0 stars. Here's what I have to do:
Write a program that presents the user w/ a choice of your 5 favorite beverages (Coke, Water, Sprite, ... , Whatever).
Then allow the user to choose a beverage by entering a number 1-5.
Output which beverage they chose.
NOTE:
I won't be creating a switch statement or making a error message if you give a value other than one that is 1-5, because that are part of the next step in the project.
using std::cout;
using std::cin;
using std::endl;
int main()
{
int UserSodaChoice;
cout > UserSodaChoice;
if (UserSodaChoice == 1)
{
cout << "I don't like Coca-Cola...";
}
if (UserSodaChoice == 2)
{
cout << "Sprite is ok I guess.";
}
if (UserSodaChoice == 3)
{
cout << "Waayyyy too much sugar.";
}
if (UserSodaChoice == 4)
{
cout << "Mountain Dew! Nice.";
}
if (UserSodaChoice == 5)
{
cout << "Eww. People don't drink Pepsi these days, it ain't the 90's.";
}
cout << "\n\n\n\t\t\t";
}Solution
Yet another way of performing the dispatch according to a user selection would be with an array of strings. Or better still, with an
Notice the
std::array, assuming your compiler is C++11 capable (which is probably the case):// Add these somewhere:
#include
#include
...
const std::array choices = {
"I don't like Coca-Cola...",
"Sprite is ok I guess.",
"Waayyyy too much sugar.",
"Mountain Dew! Nice.",
"Eww. People don't drink Pepsi these days, it ain't the 90's."
};
if (UserSodaChoice >= 1 && UserSodaChoice <= choices.size())
{
cout << choices[UserSodaChoice - 1];
}
// Else, handle invalid input...Notice the
- 1 when indexing the array. This is because UserSodaChoice ranges from 1 to 5, while the array range is 0 to N-1.Code Snippets
// Add these somewhere:
#include <array>
#include <string>
...
const std::array<std::string, 5> choices = {
"I don't like Coca-Cola...",
"Sprite is ok I guess.",
"Waayyyy too much sugar.",
"Mountain Dew! Nice.",
"Eww. People don't drink Pepsi these days, it ain't the 90's."
};
if (UserSodaChoice >= 1 && UserSodaChoice <= choices.size())
{
cout << choices[UserSodaChoice - 1];
}
// Else, handle invalid input...Context
StackExchange Code Review Q#67379, answer score: 12
Revisions (0)
No revisions yet.