Skip to the task
Layout
Back to classic view

You are looking ahead. Your place is still task 1: About.

HOMEWORKTask 16 of 17 · step 5: Task 2: a shopping listTask 2: a shopping list
Task 2: a shopping list in practice/12/

test/2/shopping.c: shopping.txt into a dynamic array of structs, the sums and the most expensive line; a bad line and no file – a message and an error code.

Checklist

  • Every task is one commit with a clear message.
  • Zero compiler warnings: the code builds with -Werror.
  • Once per topic you step through your code in the debugger (CLion, gdb).
  • Every function has preconditions and postconditions, and assert tests check them.
  • A multi-file program: .h files with Doxygen comments and their own CMake target.
  • Input only through the safe functions of your own input.h.
  • Every error code is checked (fopen, fclose, malloc and so on).
  • CI is clean: no AddressSanitizer or UBSan reports.
Details & hint

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.

practice 12 memory.c Code Diff
UNCHANGED This step does not change this file.
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* A resizable array of integers. */
typedef struct {
int *data; /* the elements in dynamic memory, or NULL */
int count; /* how many elements are stored */
int capacity; /* how many fit before it has to grow */
} IntArray;
/* An empty array: no memory yet. Before: m != NULL. */
void array_init(IntArray *m) {
assert(m != NULL);
m->data = NULL;
m->count = 0;
m->capacity = 0;
}
/* Adds x at the end; when there is no room, doubles the capacity.
Before: m != NULL. After: 1 - added, 0 - out of memory (m unchanged). */
int array_add(IntArray *m, int x) {
assert(m != NULL);
if (m->count == m->capacity) {
int new_capacity = m->capacity == 0 ? 4 : m->capacity * 2;
int *new_data = realloc(m->data, (size_t)new_capacity * sizeof *new_data);
if (new_data == NULL) {
return 0;
}
printf("Capacity: %d -> %d\n", m->capacity, new_capacity);
m->data = new_data;
m->capacity = new_capacity;
}
m->data[m->count] = x;
m->count++;
return 1;
}
/* Gives the memory back and leaves an empty array. Before: m != NULL. */
void array_free(IntArray *m) {
assert(m != NULL);
free(m->data);
array_init(m);
}
/* Returns a new copy of s in dynamic memory, or NULL if there isn't enough.
Before: s != NULL. After: the caller frees the copy with free. */
char *copy_string(const char *s) {
size_t size = strlen(s) + 1;
char *copy = malloc(size);
if (copy == NULL) {
return NULL;
}
memcpy(copy, s, size);
return copy;
}
int main(void) {
IntArray squares;
array_init(&squares);
for (int i = 1; i * i < 1000; i++) {
if (!array_add(&squares, i * i)) {
printf("Out of memory.\n");
array_free(&squares);
return EXIT_FAILURE;
}
}
printf("Squares below 1000: %d, capacity %d\n", squares.count, squares.capacity);
printf("Last: %d\n", squares.data[squares.count - 1]);
array_free(&squares);
char *name = copy_string("Ona Petraite");
if (name == NULL) {
printf("Out of memory.\n");
return EXIT_FAILURE;
}
printf("Copy: %s (%zu bytes)\n", name, strlen(name) + 1);
free(name);
return EXIT_SUCCESS;
}