Switch statements look like this:
1 2 3 4 5 6
|
switch (value)
{
case 1: /* statements */ /* optional break; */
case 2:
/* optional default: */
}
|
Upon calculating the value, the program jumps to that case. For example, if value was 2, then it would go directly to case 2. It would never wonder if 2 == 1, so that is how switches are faster.
The optional [cpde]break;[/code] is inserted into the case statements if you do not want the case to flow down. Without a break in case 1, the statements in case 2 would happen.
The optional default is what happens when value calculates to something that is not a case. Good for error reporting.
Getline is more secure because you can't "break" the cin object as easily. >> expects the type that it is extracting. If you had asked for an int, but gave it a letter, it would break. The drawback of getline is that now you have a string that needs to be converted to an int if you want to use it as an int.
I prefer to check if the cin object was broken. There is a better way to make your code, and this includes no switch or if else conditions.
Make an array (or better, vector), of soda names, and then insure that the user enters a number that is within this range:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
|
//KqQkK5
#include <iostream>
#include <vector>
#include <string>
double getNum(void);
int getInt(void);
int getIntInRange(int low, int high);
int main(void)
{
// This requires c++ 11
std::vector<std::string> drinks =
{ "Coke", "Pepsi", "Root Beer", "Sprite", "Fanta" };
// If you do not have c++ 11, you can do
//const char *d[] =
//{ "Coke", "Pepsi", "Root Beer", "Sprite", "Fanta" };
//std::vector<std::string> drinks(sizeof(d) / sizeof(const char*));
// for (unsigned int i = 0; i < drinks.size(); i++)
// drinks[i] = (std::string(d[i]));
std::cout << "Welcome to the Soda Machine\n"
<< "Please make your selection\n";
for (unsigned int i = 0; i < drinks.size(); i++)
std::cout << i + 1 << ") " << drinks[i] << std::endl;
std::cout << "\n: ";
int n = getIntInRange(1, drinks.size()) - 1;
std::cout << "You picked: " << drinks[n] << '\n';
return 0;
}
double getNum(void){
double n;
while (!(std::cin >> n))
{
std::cin.clear();
std::cin.ignore(80, '\n');
std::cout << "Numbers only please, try again: ";
}
std::cin.ignore(80, '\n');
return n;
}
int getInt(void){
double n = getNum();
while (n != static_cast<int>(n))
{
std::cout << "Integers only please, try again: ";
n = getNum();
}
return static_cast<int>(n);
}
int getIntInRange(int low, int high){
int n = getInt();
while (n < low || n > high)
{
std::cout << "Number must be in range (" <<low<<", "<<high <<")\n"
<< "Try again: ";
n = getInt();
}
return n;
}
|
With that code, all you have to do is change line 13 to be the drinks that you want.