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
|
#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;
}
|