//Sam Partovi CS1A Ch. 11, P.648, #13
/*******************************************************************************
* SIMULATE DRINK MACHINE
* ____________________________________________________________
* This program simulates a drink vending machine that accepts drink choice and
* money given to the machine.
* ____________________________________________________________
*INPUT
* name : Drink name
* cost : Cost of drink
* numInMachine : Drink quantity in stock
* moneyInserted : Money given to machine
*OUTPUT
* Menus that allow for selection and purchase of drinks
*******************************************************************************/
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
// Structure definition for Drink
struct Drink {
string name;
double cost;
int numInMachine;
};
// Function to display the drink menu
void displayMenu(Drink drinks[], int size) {
cout << "Available Drinks:" << endl;
for (int i = 0; i < size; i++) {
cout << i + 1 << ". " << drinks[i].name << " - $" << fixed <<
setprecision(2) << drinks[i].cost;
if (drinks[i].numInMachine == 0)
cout << " (Sold Out)";
cout << endl;
}
cout << "99. Quit and Display Machine Earnings" << endl;
}
// Main function
int main() {
// Array of 5 drinks
Drink drinks[5] = {
{"Cola", 0.75, 20},
{"Root Beer", 0.75, 20},
{"Lemon-Lime", 0.75, 20},
{"Grape Soda", 0.80, 20},
{"Cream Soda", 0.80, 20}
};
int choice;
double moneyInserted;
do {
displayMenu(drinks, 5);
cout << "Select a drink (1-5) or type 99 to quit: ";
cin >> choice;
if (choice >= 1 && choice <= 5) {
if (drinks[choice - 1].numInMachine == 0) {
cout << "Sorry, " << drinks[choice - 1].name <<
" is sold out." << endl;
continue; // Skip the rest of the loop for this iteration
}
// Get money from user
do {
cout << "Insert money ($0 to $1): ";
cin >> moneyInserted;
if (moneyInserted < 0 || moneyInserted > 1) {
cout << "Invalid amount. Please insert money between $0 and"
"$1." << endl;
}
} while (moneyInserted < 0 || moneyInserted > 1);
if (moneyInserted >= drinks[choice - 1].cost) {
double change = moneyInserted - drinks[choice - 1].cost;
cout << "Dispensing " << drinks[choice - 1].name << ". Your "
"change is $" << fixed << setprecision(2) << change << endl;
drinks[choice - 1].numInMachine--;
} else {
cout << "Not enough money inserted. Returning $" << fixed <<
setprecision(2) << moneyInserted << endl;
}
} else if (choice != 99) {
cout << "Invalid selection! Please select a valid option." << endl;
}
} while (choice != 99); // End of the main loop
return 0;
}