Learn/C/15. Final project: shop inventory
Lesson 15 of 15
Sign in

C, lesson 15

Final project: shop inventory

You now know enough C to write a real, if small, program. In this project you build the back office of a corner shop: it reads commands one line at a time, keeps track of stock and money, reports errors politely, and prints a sorted report on request. Nothing here is new; the challenge is putting the pieces together cleanly.

Plan before you type

Larger programs go better when you decide on the data first and the code second.

Data. One struct describes an item, and an array of them is the inventory:

Storing money as whole cents avoids the rounding surprises of double (0.1 + 0.2 is not exactly 0.3). Convert to dollars only when printing, with / 100 and % 100.

Functions. Give each job its own small function so main reads like a table of contents:

One exercise to try what you just read.

Exercise 1

Corner shop

Press Ctrl Enter or Check to test your code.

  • struct item *find_item(const char *name) returns a pointer to the matching item, or nullptr. Returning a pointer lets the caller change the item in place.
  • void print_money(long long cents) prints 12.34.
  • One function per command: do_add, do_sell, do_report.

Input. Each command is one line, so read lines with fgets and then pull the fields out with sscanf, which works like scanf but reads from a string. Its return value tells you how many fields it found, which is how you detect a malformed command:

Inside do_add, sscanf(line, "%*s %20s %d %d", name, &qty, &price) skips the command word (the * means "read but don't store") and should return 3.

Sorting the report. Copy nothing: qsort the stock array by name right before printing. Because find_item searches by name, the order of the array never matters to the rest of the program.

Edge cases are part of the spec

Good programs decide what happens with bad input instead of crashing. Before you start, read the error rules below and think about where each check belongs. Validate first, then change state: a rejected command must leave the inventory exactly as it was.

Build it in steps

  1. Read lines and echo the command word, to prove the loop works.
  2. Implement add and report together, so you can see your data.
  3. Add sell with its two error cases.
  4. Handle the bad-input and unknown-command cases last.

Run your program after every step. Small steps make bugs easy to find.

Further reading

  • cppreference: sscanf
  • cppreference: fgets
  • cppreference: qsort
  • cppreference: Struct declaration

Read commands, one per line, until the input ends. Names are one word of at most 20 characters; quantities and prices are integers, and prices are in cents. There are at most 100 different items.

CommandEffect and output
add <name> <qty> <price>Add qty to the item (creating it if new) and set its price. Print Added <qty> <name>.
sell <name> <qty>Remove qty from stock and add qty × price to revenue. Print Sold <qty> <name> for <amount>.
reportPrint --- report ---, then one line per item sorted by name (strcmp order) as <name> <qty> @ <price>, then Stock value: <sum of qty × price> and Revenue: <revenue>.

Money is always printed as dollars with two digits of cents, like 4.00 or 12.05.

Errors (print the message and change nothing):

  • add without all three numbers, with qty ≤ 0, or with price < 0: Error: bad input
  • sell without a name and quantity, or with qty ≤ 0: Error: bad input
  • sell of an item that doesn't exist: Error: no item <name>
  • sell of more than is in stock: Error: only <stock> <name> left
  • any other command word: Error: unknown command <word>

Blank lines are ignored.

struct item {
    char name[21];
    int quantity;
    int price;          // cents, so money stays exact
};

struct item stock[100];
int item_count = 0;
long long revenue = 0;  // cents
char line[128];
while (fgets(line, sizeof line, stdin) != nullptr) {
    char command[16];
    if (sscanf(line, "%15s", command) != 1) {
        continue;                       // blank line
    }
    if (strcmp(command, "add") == 0) {
        do_add(line);
    } // ...
}
Input:
add apple 10 50
add pear 4 75
sell apple 2
sell pear 9
sell kiwi 1
report
Output:
Added 10 apple
Added 4 pear
Sold 2 apple for 1.00
Error: only 4 pear left
Error: no item kiwi
--- report ---
apple 8 @ 0.50
pear 4 @ 0.75
Stock value: 7.00
Revenue: 1.00