+1 (315) 557-6473 

Create a Simulation of a Vending Machine in C++

In this guide, we will explore a comprehensive C++ program designed to simulate a vending machine. We'll dissect the code into smaller, more digestible sections and provide a detailed overview of each part. This will enable you to gain a deep understanding of how this vending machine simulation works. Whether you're a student learning C++ or simply curious about how vending machines are programmed, this article will walk you through the code step by step. So, let's embark on this journey of unraveling the inner workings of our virtual vending machine.

Demystifying C++ Vending Machine Simulation

Explore the intricacies of C++ programming through our detailed guide on building a virtual vending machine in C++. This hands-on project will not only enhance your coding skills but also help you understand fundamental concepts. It's a valuable resource to help your C++ assignment and master the art of practical programming. Whether you're a student seeking to complete your programming homework or a budding coder eager to refine your skills, this C++ vending machine simulation offers a real-world example that makes learning enjoyable and effective. Dive into the code, experiment with it, and gain the confidence to tackle your C++ assignments with ease.

Header and Library Inclusions

```cpp #include "LinkedList.h" #include < fstream > #include < iomanip > #include < iostream > #include < map > #include < sstream > #include < string > ```

In the header and library inclusions section, we include essential header files and libraries that are pivotal for the functionality of our vending machine simulation program. These libraries enable us to work with data structures, file operations, and standard input/output, facilitating the core operations of the program. By including these headers, we ensure that our program has access to the necessary tools and functionalities, which are crucial for a seamless vending machine simulation.

Constants

```cpp #define DEFAULT_COIN_VALUE 10 #define DEFAULT_STOCK_VALUE 10

In the constants section, we define and set default values for coins and stock within our program. These constants act as reference points and initial values for the vending machine's operation. By setting default values for coins and stock, we establish a baseline for the program's behavior, making it easier to manage and manipulate the vending machine's inventory and coin denominations. These constants play a vital role in ensuring the vending machine starts with predefined values.

Green String Function

```cpp string greenStr(string s) { return "\033[1;32m" + s + "\033[0m"; } ```

The green string function is a utility function that enhances the visual representation of our program's output. It takes a string as input and wraps it in ANSI escape codes, giving it a distinctive green color. This function is used to highlight and emphasize specific text in the program's output, making it more visually appealing and user-friendly. It enhances the user experience by providing a clear and aesthetically pleasing interface, especially when displaying important information and prompts. The green string function is a valuable tool for improving the overall presentation of our vending machine simulation.

File Reading Functions

readStockFile

```cpp void readStockFile(string filename, LinkedList *stockList) { fstream inputFile; inputFile.open(filename, ios::in); if (inputFile.is_open()) { // Checking whether the file is open string tp; while (getline(inputFile, tp)) { stringstream ss(tp); string priceStr, dollarsStr, centsStr, quantityStr; Price price; Stock *stock = new Stock(); getline(ss, stock->id, '|'); getline(ss, stock->name, '|'); getline(ss, stock->description, '|'); getline(ss, priceStr, '|'); getline(ss, quantityStr, '|'); stringstream priceStream(priceStr); getline(priceStream, dollarsStr, '.'); getline(priceStream, centsStr, '.'); price.dollars = stoul(dollarsStr); price.cents = stoul(centsStr); stock->price = price; stock->on_hand = stoul(quantityStr); stockList->addSorted(stock); } inputFile.close(); // Close the file object. } } ```

The readStockFile function plays a crucial role in our vending machine simulation by reading stock information from a specified file. It meticulously parses the data within the file, extracting details such as item ID, name, description, price, and quantity available. This function then utilizes the extracted information to populate a linked list with stock items. The result is a comprehensive inventory of items that the vending machine will offer to customers. The readStockFile function ensures that the vending machine's stock is accurately loaded and ready for user interaction.

readCoinFile

```cpp void readCoinFile(string filename, map &coins) { fstream inputFile; inputFile.open(filename, ios::in); if (inputFile.is open()) { // Checking whether the file is open string tp; while (getline(inputFile, tp)) { stringstream ss(tp); string denomStr, quantityStr; getline(ss, denomStr, ','); getline(ss, quantityStr, ','); int denom; Coin coin; denom = stoul(denomStr); coin.count = stoul(quantityStr); if (denom == 1000) { coin.denom = TEN_DOLLARS; } else if (denom == 500) { coin.denom = FIVE_DOLLARS; } else if (denom == 200) { coin.denom = TWO_DOLLARS; } else if (denom == 100) { coin.denom = ONE_DOLLAR; } else if (denom == 50) { coin.denom = FIFTY_CENTS; } else if (denom == 20) { coin.denom = TWENTY_CENTS; } else if (denom == 10) { coin.denom = TEN_CENTS; } else if (denom == 5) { coin.denom = FIVE_CENTS; } coins[denom] = coin; } inputFile.close(); // Close the file object. } } ```

In the context of our vending machine program, readCoinFile serves as an essential function responsible for reading coin information from a designated file. This function carefully parses the data within the file, extracting vital details about coin denominations and their respective counts. With this information in hand, readCoinFile proceeds to populate a map with coin denominations and their corresponding counts. This map acts as the foundation for managing the vending machine's available change. By reading and processing the coin file, our vending machine can provide users with accurate change during transactions, enhancing their overall experience.

Display Menu

```cpp void displayMenu() { cout << "Main Menu:" << endl; cout << "\t1. Display Items" << endl; cout << "\t2. Purchase Items" << endl; cout << "\t3. Save and Exit" << endl; cout << "Administrator-Only Menu:" << endl; cout << "\t4. Add Item" << endl; cout << "\t5. Remove Item" << endl; cout << "\t6. Display Coins" << endl; cout << "\t7. Reset Stock" << endl; cout << "\t8. Reset Coins" << endl; cout << "\t9. Abort Program" << endl; cout << "Select your option (1-9): "; } ```

The Display Menu function is the face of our vending machine program, as it serves as the primary interface for both users and administrators. This function takes charge of displaying the main menu, presenting a range of options that allow users to interact with the vending machine. Users can choose to explore available items, make purchases, or save and exit the program. For administrators, additional options are available, including the ability to add new items, remove existing ones, manage coin denominations, and reset stock and coin counts. The Display Menu function ensures a user-friendly and intuitive experience while navigating the vending machine's features. It acts as the central hub for controlling and navigating the program's functionalities, making it an integral part of our simulation.

Display Items

```cpp void displayItems(LinkedList *stockList) { cout << "Items Menu" << endl; cout << "----------" << endl; cout << "ID | Name | Available | Price" << endl; cout << "-------------------------------------------------------------" << endl; Node *curr = stockList->getHead(); while (curr != nullptr) { cout << setw(5) << left << curr->data->id << "|" << setw(41) << left << curr->data->name << "|" << setw(11) << left << curr->data->on_hand << "|" << greenStr("$") << setw(2) << right << curr->data->price.dollars << "." << setw(2) << setfill('0') << curr->data->price.cents << endl << setfill(' '); curr = curr->next; } } ```

The Display Items function serves as a pivotal component of our vending machine simulation, offering users a comprehensive view of the available items. It meticulously lists these items, displaying essential information such as their unique IDs, names, current availability, and corresponding prices. This user-friendly interface empowers customers to make informed choices, providing clarity and transparency in their decision-making process. Display Items ensures a smooth and convenient shopping experience within our vending machine simulation.

Purchase Item

```cpp void purchaseItem(LinkedList *stockList, map &coins) { cout << "Purchase Item" << endl; cout << "-------------" << endl; string id; cout << "Please enter the id of the item you wish to purchase: "; getline(cin, id); Stock *stock = stockList->getById(id); cout << "You have selected \"" << stock->name << " - " << stock->description << "\". This will cost you " << greenStr("$") << setw(2) << right << stock->price.dollars << "." << setw(2) << setfill('0') << stock->price.cents << setfill(' ') << "." << endl; cout << "Please hand over the money - type in the value of each note/coin in " "cents." << endl; cout << "Press enter or ctrl-d on a new line to cancel this purchase:" << endl; int remaining = 100 * stock->price.dollars + stock->price.cents; bool failed = false; map added; while (remaining > 0) { cout << "You still need to give us " << greenStr("$") << remaining / 100 << "." << setw(2) << setfill('0') << remaining % 100 << setfill(' ') << ": "; string amountStr; getline(cin, amountStr); int amount = stoul(amountStr); if (coins.find(amount) != coins.end()) { if (added.find(amount) == added.end()) { added[amount] = 0; } added[amount] = added[amount] + 1; remaining -= amount; } else { cout << "Error: " << greenStr("$") << " " << amount / 100 << "." << setw(2) << setfill('0') << amount % 100 << setfill(' ') << " is not a valid denomination of money. Please try again." << endl; } } failed = !pickChange(coins, added, -remaining, stock->name); if (!failed) { stock->on_hand--; } } ```

The Purchase Item function provides users with the ability to interact with the vending machine, select an item for purchase, input the necessary amount of money, and receive change if the transaction is successfully completed. This crucial function transforms the vending machine into a dynamic, user-centric system, allowing customers to make selections and transactions seamlessly. Users can choose their desired items, make payments, and receive their purchases, making it a user-friendly and efficient way to simulate real vending machine operations.

Add Item

```cpp void addItem(LinkedList *stockList) { Stock *stock = new Stock(); string priceStr; cout << "The id of the new stock will be: "; getline(cin, stock->id); cout << "Enter the item name: "; getline(cin, stock->name); cout << "Enter the item description: "; getline(cin, stock->description); cout << "Enter the price for the item: "; getline(cin, priceStr); stringstream priceStream(priceStr); string dollarsStr, centsStr; getline(priceStream, dollarsStr, '.'); getline(priceStream, centsStr, '.'); stock->price.dollars = stoul(dollarsStr); stock->price.cents = stoul(centsStr); stock->on_hand = DEFAULT_STOCK_VALUE; stockList->addSorted(stock); cout << "This item \"" << stock->name << " - " << stock->description << "\" has now been added to the menu." << endl; } ```

In the administrative realm of our vending machine simulation, the Add Item function plays a vital role. It enables administrators to expand the vending machine's inventory by adding new items. This function empowers administrators to input essential details about the new item, such as its ID, name, description, and price. Once added, the new item becomes part of the vending machine's offerings, enriching the selection for customers. The Add Item function streamlines the process of updating the vending machine's stock, making it a valuable tool for administrators.

Remove Item

```cpp void removeItem(LinkedList *stockList) { string id; cout << "Enter the item id to remove from the menu: "; getline(cin, id); Node *node = stockList->removeById(id); if (node != nullptr) { Stock *stock = node->data; cout << "\"" + stock->id + " - " + stock->name + " - " + stock->description + "\" has now been removed from the system."; delete node; } } ```

The Remove Item function empowers administrators to efficiently manage the vending machine's stock by providing the capability to remove specific items from the inventory. This feature is essential for maintaining an up-to-date selection of items, allowing administrators to make necessary adjustments to the vending machine's offerings. By selecting an item for removal, administrators can ensure that the vending machine's stock remains relevant and aligned with customer preferences.

Reset Stock Count

```cpp void resetStockCount(LinkedList *stockList) { Node *curr = stockList->getHead(); while (curr != nullptr) { curr->data->on_hand = DEFAULT_STOCK_VALUE; curr = curr->next; } cout << "All stock has been reset to the default level of " << DEFAULT_STOCK_VALUE << endl; } ```

In the realm of stock management, the Reset Stock Count function proves to be invaluable. It simplifies the process of restoring all item counts to their default values. This function is particularly useful in scenarios where stock levels need to be replenished, ensuring that each item's availability is set back to the predetermined default. Reset Stock Count offers an efficient and systematic approach to managing the vending machine's inventory, making it an essential tool for administrators.

Reset Coin Count

```cpp void resetCoinCount(map &coins) { int denoms[] = {5, 10, 20, 50, 100, 200, 500, 1000}; for (int i = 0; i < 8; i++) { coins[denoms[i]].count = DEFAULT_COIN_VALUE; } cout << "All coins have been reset to the default level of " << DEFAULT_COIN_VALUE << endl; } ```

The Reset Coin Count function is an essential administrative feature that simplifies the task of restoring coin counts for all coin denominations to their default values. This capability ensures that the vending machine is well-equipped to provide accurate change during transactions. By resetting the coin counts, administrators can maintain a consistent and reliable supply of change, guaranteeing a smooth and error-free customer experience.

Display Coins

```cpp void displayCoins(map &coins) { cout << "Coins Summary" << endl; cout << "-------------" << endl; cout << "Denomination | Count " << endl; string text[] = {"5 Cents", "10 Cents", "20 Cents", "50 Cents", "1 Dollar", "2 Dollar", "5 Dollar", "10 Dollar"}; cout << "---------------------------" << endl; int denoms[] = {5, 10, 20, 50, 100, 200, 500, 1000}; for (int i = 0; i < 8; i++) { cout << setw(16) << left << text[i] << "|" << setw(10) << right << coins[denoms[i]].count << endl; } } ```

The Display Coins function provides users and administrators with a clear and concise summary of the vending machine's coin denominations and their respective counts. This visual representation offers a quick overview of the available coin inventory, making it easy to assess the vending machine's capacity to provide change. Whether for users looking to make informed transactions or administrators seeking to manage coin denominations, Display Coins serves as a valuable reference, ensuring transparency and efficiency in coin-related operations.

Save Data

```cpp void saveData(string stockFilename, string coinsFilename, LinkedList* stockList, map& coins) { Node* curr = stockList->getHead(); fstream fout(stockFilename); while (curr != nullptr) { fout << curr->data->id << "|" << curr->data->name << "|" << curr->data->description << "|" << curr->data->price.dollars << "." << curr->data->price.cents << "|" << curr->data->on_hand << endl; curr = curr->next; } fout.close(); fstream fout2(coinsFilename); int denoms[] = {5, 10, 20, 50, 100, 200, 500, 1000}; for (int i = 7; i >= 0; i--) { fout2 << denoms[i] << "," << coins[denoms[i]].count << endl; } fout2.close(); } ```

The Save Data function is a pivotal feature in our vending machine simulation, responsible for preserving the crucial stock and coin information. By executing this function, the program diligently stores the up-to-date stock and coin details in separate files, ensuring that the data remains intact and accessible for future use. This data-saving capability is essential for maintaining accurate records and supporting the longevity of the vending machine simulation.

Main Function

```cpp int main(int argc, char **argv) { /* validate command line arguments */ string stockFileName(argv[1]); string coinsFileName(argv[2]); LinkedList *stockList = new LinkedList(); map coins; readStockFile(stockFileName, stockList); readCoinFile(coinsFileName, coins); bool isOver = false; bool save = false; while (!isOver) { displayMenu(); string tmp; int choice; getline(cin, tmp); choice = stoi(tmp); if (choice == 1) { displayItems(stockList); } else if (choice == 2) { purchaseItem(stockList, coins); } else if (choice == 3) { isOver = true; save = true; } else if (choice == 4) { addItem(stockList); } else if (choice == 5) { removeItem(stockList); } else if (choice == 6) { displayCoins(coins); } else if (choice == 7) { resetStockCount(stockList); } else if (choice == 8) { resetCoinCount(coins); } else if (choice == 9) { isOver = true; } else { cout << "Invalid input" << endl; } cout << endl; } if (save) { saveData(argv[1], argv[2], stockList, coins); } delete stockList; return EXIT_SUCCESS; } ```

At the core of our vending machine program lies the Main Function, serving as the entry point to the entire system. This function takes the lead in orchestrating the main program loop, efficiently handling user input and facilitating the program's termination. The Main Function is the brain behind our simulation, directing the flow of the program and calling various functions based on user input to emulate the vending machine's day-to-day operations. It bridges the gap between users, administrators, and the vending machine itself, ensuring a smooth and interactive experience.

Node and LinkedList Classes

In addition to the vending machine's core functions, our code incorporates specialized classes to manage stock data effectively. The Node and LinkedList classes are instrumental in organizing and storing stock-related information. Nodes serve as individual units containing stock data, while the LinkedList class orchestrates the management and manipulation of these nodes, ensuring that the stock remains organized and accessible. These classes play a vital role in structuring the program's data and are essential components for the seamless operation of our vending machine simulation.

Coin Class

The Coin class is a fundamental component of our vending machine simulation, designed to handle all aspects of coin-related information. It serves as the backbone for managing coin denominations and their respective counts. This class encapsulates essential details about coins, making it possible for the program to maintain a comprehensive record of available denominations and their quantities. The Coin class is integral to providing users with accurate change during transactions, ensuring that the vending machine operates smoothly and efficiently.

pickChange Function

```cpp bool pickChange(std::map& coins, std::map& added, int amount, string name) { int denoms[] = {1000, 500, 200, 100, 50, 20, 10, 5}; string sts[] = {"$10", "$5", "$2", "$1", "50c", "20c", "10c", "5c"}; unsigned used[] = {0, 0, 0, 0, 0, 0, 0, 0}; int curr = amount; for (int i = 0; i < 8; i++) { if (added.find(denoms[i]) == added.end()) { added[denoms[i]] = 0; } int addedCoin = added[denoms[i]]; used[i] = curr / denoms[i]; used[i] = std::min(used[i], addedCoin + coins[denoms[i]].count); curr -= used[i] * denoms[i]; } if (curr == 0) { cout << "Here is your " << name << " and your change of $" << std::setw(2) << std::right << amount / 100 << "." << std::setw(2) << std::setfill('0') << amount % 100 << std::setfill(' ') << ":"; for (int i = 0; i < 8; i++) { coins[denoms[i]].count += added[denoms[i]] - used[i]; for (int j = 0; j < used[i]; j++) { cout << " " << sts[i]; } } cout << std::endl; return true; } else { cout << "AMOUN " << curr << std::endl; return false; } } ```

The pickChange function is a critical piece of our vending machine's transaction logic. Its primary purpose is to calculate and return change to the user based on the coins available in the machine and any coins added during a purchase. This function ensures that customers receive the correct change when making a transaction, enhancing their overall experience and trust in the vending machine. It plays a pivotal role in the vending machine's core functionality, guaranteeing the accuracy and reliability of every transaction. The pickChange function is a key contributor to the program's user-friendly and customer-centric design.

Conclusion

In conclusion, our C++ program provides a realistic simulation of a vending machine. Users can interact with it, and administrators can efficiently manage stock and coin information. This project not only serves as an educational tool but also demonstrates the practical implementation of fundamental programming concepts. By exploring this code, you'll gain valuable insights into file handling, data structures (linked lists and maps), and the intricacies of user input processing.

Moreover, this simulation project serves as an excellent starting point for those looking to delve deeper into C++ programming. Whether you're a student learning the language or a curious enthusiast, this resource equips you with the skills to tackle real-world coding challenges. As you continue your programming journey, remember that learning by doing is often the most effective way to master a language, and this vending machine simulation is a great example of hands-on learning. So, go ahead and explore the code, experiment with it, and discover the art and science of C++ programming in action.