Checking Stock
Part of the Logic & Flow section of Coddy's C++ journey — lesson 32 of 56.
Challenge
EasyContinue building your inventory tracking system by implementing the functionality to check the current stock level of specific items. This lesson demonstrates how to safely query a map for item information and handle cases where items may not exist in the inventory.
The following inputs will be provided:
- An integer
nrepresenting the number of stock queries to perform - Then
nstrings representing item names to check
Your program should:
- Start with the following initial inventory:
inventory["apples"] = 50;
inventory["bananas"] = 30;
inventory["oranges"] = 25;
inventory["grapes"] = 40; - Read the number of stock queries
- For each query, read an item name
- Use the
.count()method to check if the item exists in the inventory map - If the item exists, print its current stock quantity
- If the item does not exist, print a message indicating it was not found
- After all queries, print a summary of the total number of different items currently in inventory
Use the following exact output format:
For each stock query:
[item_name]: [quantity] in stockFor items not found:
[item_name]: Item not foundSummary at the end:
Total items in inventory: [number_of_items]Use the .count() method to safely check if each item exists before accessing its value. If inventory.count(itemName) returns 1, the item exists and you can safely access inventory[itemName] to get its quantity. If it returns 0, the item doesn't exist. Use the .size() method on the map to get the total number of different items in the inventory for the final summary.
Try it yourself
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
// Initialize the inventory with existing items
map<string, int> inventory;
inventory["apples"] = 50;
inventory["bananas"] = 30;
inventory["oranges"] = 25;
int n;
cin >> n;
for (int i = 0; i < n; i++) {
string itemName;
int quantity;
cin >> itemName >> quantity;
inventory[itemName] += quantity;
cout << "Added " << quantity << " " << itemName << ". New total: " << inventory[itemName] << endl;
}
cout << "Final Inventory:" << endl;
for (const auto& item : inventory) {
cout << item.first << ": " << item.second << endl;
}
return 0;
}All lessons in Logic & Flow
1Pointers and Memory
What is a Pointer?Address-Of OperatorDereference OperatorNull PointersPointers and ArraysDynamic Memory with 'new'Freeing Memory with 'delete'Recap - Pointer Practice2Vectors (Dynamic Arrays)
Introducing std::vectorCreating a VectorAdding ElementsAccessing ElementsVector SizeIterating with a For LoopRange-Based For LoopRemoving ElementsRecap - Vector Operations5Project: Inventory Tool
Project SetupAdding and Updating Items