#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
#include <sstream>
using namespace std; //this should not be used, use std::scope
string input; //string input
int item = 0;
float total;
std::vector<string> menuItems = {"Popcorn", "Coconut Clusters", "Granola Bar", "Trail Mix", "Chocolate"};
std::vector<float> cost = {2, 3, 2.50, 1.50, 1};
void vendingMachine()
{
for (int i = 0; i < 5; i++)
cout << i + 1 << ". " << menuItems[i] << ": $" << cost[i] << endl;
}
void enterSelection()
{
total = 0;
int flag = 0; //flag for input errors
cout << "Enter your selection: ";
cin >> input;
try
{
item = stoi(input); //convert to int
}
catch (exception &e)
{
//std::cout << e.what();
flag = -1; //if not set flag
}
if (flag != -1 && item < 5 && item > 0) //only execute with no errors
{
item--;
cout << menuItems[item] << ": $" << cost[item] << " has been added to cart." << endl;
total = total + cost[item];
flag = 0; //reset flag
}
}
void checkout()
{
cout << " " << endl;
cout << "Proceding to checkout..." << endl;
cout << "========================" << endl;
cout << "Amount due: $" << total << endl;
cout << "Insert money here: $" << flush;
float money;
cin >> money;
while (money < total)
{
float amountOwed = total - money;
cout << "Please insert another $" << amountOwed << endl;
cout << "Enter amount: $" << flush;
float payment;
cin >> payment;
money += payment;
}
if (money > total)
{
float change = money - total;
cout << "Thank you! You have $" << change << " change." << endl;
}
if (money == total)
{
cout << "Thank you! Have a nice day!." << endl;
}
exit(0); //exit after checkout
}
void add()
{
cout << "What item would you like to add: " << flush;
string add;
cin >> add;
menuItems.push_back(add);
}
void remove()
{
cout << "What item would you like to remove (enter a number): " << flush;
int remove;
cin >> remove;
menuItems.erase(menuItems.begin() + remove);
}
int main()
{
cout.precision(2);
cout << std::fixed;
cout << "Vending Machine" << endl;
cout << "----Items------" << endl;
vendingMachine();
cout << "Enter c to checkout" << endl;
cout << "Enter a to add items" << endl;
cout << "Enter r to remove items" << endl;
enterSelection();
while(1) // infinite cycle will exit in checkout
if (!input.compare("c"))
{
checkout();
}
else if (!input.compare("a"))
{
add();
}
else if (!input.compare("r"))
{
remove();
}
else
{
cout << "Please enter a number or press c to checkout, a to add item, or r to remove item: ";
enterSelection(); //execute enter selection again
}
return 0;
}