BETA Try the new lesson view
Theory

Task 2: a shopping list

The file test/2/shopping.c, the program test2_shopping.

The task

The program reads the file shopping.txt (from the folder it is run in). Each line is one item: a name (one word, up to 30 bytes), a quantity (a whole number, at least 1) and a price (with a dot, not negative):

Milk 2 1.29
Bread 1 0.99
Coffee 2 4.49
Apples 6 0.35
Cheese 1 3.80
Tea 3 1.50

This test/2/shopping.txt is already there, and course_data(shopping.txt) copies it to where ▶ runs the program. Edit the original: the next Build refreshes the copy.

Print every item with its sum, the total and the most expensive line (the largest quantity × price; of several equal ones, the first):

Items: 6
Milk: 2 x 1.29 = 2.58
Bread: 1 x 0.99 = 0.99
Coffee: 2 x 4.49 = 8.98
Apples: 6 x 0.35 = 2.10
Cheese: 1 x 3.80 = 3.80
Tea: 3 x 1.50 = 4.50
Total: 22.95
Most expensive: Coffee (8.98)
  • No file – Cannot open the file shopping.txt. and return EXIT_FAILURE;.
  • A bad line (a part missing, 4,49, quantity 0, a negative price, junk at the end, an empty line) – shopping.txt, line 3: bad format. and EXIT_FAILURE. Don't print the other lines.
  • An empty file – Items: 0 and Total: 0.00, without Most expensive.

How to write it

  • typedef struct { char name[MAX_ITEM_NAME + 1]; int quantity; double price; } Item;
  • There is no limit on the number of items: they live in a dynamic array that grows via realloc and a temporary pointer, like topic 12's IntArray. There must be no MAX_ITEMS.
  • Read the lines with fgets, not fscanf. sscanf(line, "%30s %d %lf %c", ...) helps take one line apart: the line is good when it returns 3 – the fourth %c catches junk at the end.
  • Return errors as a code (an enum), not exit inside a function. On every path – fclose and free: GitHub CI with LeakSanitizer catches a leak on an error path too.
  • Every function has a contract and an assert.

Tests

Each test runs the program in its own folder: in the first shopping.txt is the example above (6 items: the capacity grows 4 → 8), in the second line 3 is Coffee 2 4,49, in the third there is no file. The second and third tests expect an error code.

When ctest --preset debug -L test2 shows 100% tests passed, 0 tests failed out of 7, commit: Solve test 2: shopping list.