Menu
Coddy logo textTech

Checking Stock

Part of the Logic & Flow section of Coddy's C++ journey — lesson 32 of 56.

challenge icon

Challenge

Easy

Continue 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 n representing the number of stock queries to perform
  • Then n strings representing item names to check

Your program should:

  1. Start with the following initial inventory:
    inventory["apples"] = 50;
    inventory["bananas"] = 30;
    inventory["oranges"] = 25;
    inventory["grapes"] = 40;
  2. Read the number of stock queries
  3. For each query, read an item name
  4. Use the .count() method to check if the item exists in the inventory map
  5. If the item exists, print its current stock quantity
  6. If the item does not exist, print a message indicating it was not found
  7. 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 stock

For items not found:

[item_name]: Item not found

Summary 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