Skip to content

Assemble the Report

The Course
•
30 min study

Every part of the report already exists: bounded reading from Day 6, the parser, the capacity-checked add_session, and the total from Day 4. Assembling them is mostly a matter of deciding who does what. The project splits three jobs across three files. main.c reads lines and counts rejections. report.c validates text and stores accepted sessions. report.h states the contracts between them. Because each helper keeps its own promises, main can be short: it never indexes the array itself, never converts a digit and never checks the range.

Predict and run

This small loop has the same shape as the report's main loop. Predict both numbers.

Predict before running C
#include <stdio.h>

int main(void) {
    int accepted = 0;
    int rejected = 0;
    int values[3] = {25, 0, 10};
    for (int i = 0; i < 3; i++) {
        if (values[i] < 1) {
            rejected++;
            continue;
        }
        accepted++;
    }
    printf("%d %d\n", accepted, rejected);
    return 0;
}
Check your prediction
Text
2 1

continue ends the current iteration at once and goes on to the next one, so a rejected value never reaches accepted++. Move accepted++ above the if and the result becomes 3 and 1: the bad value was counted on both sides. Each record must land in exactly one count.

Trace one line through the files

Follow the line 25 and then the line bad through the program in the editor at the end of this lesson.

  1. fgets(line, sizeof line, stdin) reads into a 32-byte buffer. "25\n" fits, with room to spare.
  2. The overlong check, strchr(line, '\n') == NULL && !feof(stdin), is false because the newline is present.
  3. parse_minutes(line, &minutes) accepts the digits and the newline and stores 25. For "bad" it returns 0 and minutes keeps its starting 0.
  4. add_session(sessions, &count, minutes) checks the capacity and range, stores the session and increments count.
  5. The two calls are joined in one condition: !parse_minutes(...) || !add_session(...). If parsing fails, short-circuiting means add_session is never called, so an unparsed value can never be stored. If either step fails, rejected++ runs once.

That one || is the whole policy: a line counts as a session only if it passes both checks, and every other line counts as one rejection.

The overlong line, step by step

A line of 40 digits does not fit in 32 bytes. fgets returns the first 31 characters with no newline. The program does not try to parse that fragment. It reads and discards characters with getchar until it reaches the newline or EOF, counts one rejection, and uses continue to start the next line cleanly. Without the drain, the rest of the line would arrive as a second fragment and might even parse as a valid number.

Two boundaries are worth tracing. A final line with no newline, such as 25 at the very end of the input, also lacks '\n', but feof(stdin) is true, so it is parsed normally. And a line of exactly 30 characters plus its newline fills 31 bytes and fits; one more character makes it overlong.

Errors are not end-of-file

fgets returns NULL both at the end of the input and when reading fails. After the loop, ferror(stdin) tells the two apart. On a real read error, the program writes a message to stderr, the error stream, and returns 1 from main. A nonzero exit status tells scripts and other programs that the run failed, while the normal report on stdout is kept for successful runs.

Practice

Exercise

Your turn

Simulate the report's policy over an array. For {25, 0, 10, 181, 30, 20}, store valid durations (1 through 180) in a three-slot array. A value is rejected if it is invalid or if the array is already full. Use one if with ||, so that a full array is only checked for valid values, and print:

Text
Stored 3, total 65, rejected 3
Your workspace C
#include <stdio.h>

int main(void) {
    int input[6] = {25, 0, 10, 181, 30, 20};
    int stored[3] = {0};
    int count = 0;
    // Write your solution here.
    return 0;
}
Hint 1: the idea

Write a small store function that returns 0 when the collection is full and 1 after storing. Then the loop body mirrors main.c: if the value is invalid, or storing it fails, count a rejection.

Hint 2: a first step

Write valid and store first, and test store on its own: call it four times on the empty three-slot array from main and print each result. You should see 1, 1, 1 and then 0. Only then write the loop over input.

Show one solution
C
#include <stdio.h>

int valid(int minutes) {
    return minutes >= 1 && minutes <= 180;
}

int store(int values[], int *count, int value) {
    if (*count >= 3) {
        return 0;
    }
    values[*count] = value;
    (*count)++;
    return 1;
}

int main(void) {
    int input[6] = {25, 0, 10, 181, 30, 20};
    int stored[3] = {0};
    int count = 0;
    int rejected = 0;
    for (int i = 0; i < 6; i++) {
        if (!valid(input[i]) || !store(stored, &count, input[i])) {
            rejected++;
        }
    }
    int total = 0;
    for (int i = 0; i < count; i++) {
        total += stored[i];
    }
    printf("Stored %d, total %d, rejected %d\n", count, total, rejected);
    return 0;
}
Text
Stored 3, total 65, rejected 3

0 and 181 were rejected by valid, and 20 by store, because the array was full after 30. Each value produced exactly one outcome, so stored plus rejected equals the six inputs, a check you can apply to any run of the report. The total loop uses count, never the capacity. Next you will test the real helpers at their boundaries.

Run the complete program

The input box is prefilled with 25, 10, bad, 180 and 0 on separate lines.

Study report C
#include "report.h" #include <stdio.h> #include <string.h> int main(void) { struct Session sessions[SESSION_CAPACITY] = {0}; int count = 0; int rejected = 0; char line[32]; while (fgets(line, sizeof line, stdin) != NULL) { if (strchr(line, '\n') == NULL && !feof(stdin)) { /* Consume the rest of one overlong record, not as extra sessions. */ int ch; while ((ch = getchar()) != '\n' && ch != EOF) { } rejected++; continue; } int minutes = 0; if (!parse_minutes(line, &minutes) || !add_session(sessions, &count, minutes)) { rejected++; } } if (ferror(stdin)) { fprintf(stderr, "Could not read input\n"); return 1; } printf("Sessions: %d\n", count); printf("Total: %d minutes\n", total_minutes(sessions, count)); printf("Rejected: %d\n", rejected); return 0; } #include "report.h" #include <stddef.h> int parse_minutes(const char *text, int *out) { if (text == NULL || out == NULL || *text == '\0') { return 0; } int value = 0; int i = 0; while (text[i] >= '0' && text[i] <= '9') { int digit = text[i] - '0'; /* Reject before multiplication: even a very long number cannot overflow. */ if (value > (MAX_MINUTES - digit) / 10) { return 0; } value = value * 10 + digit; i++; } if (i == 0 || value < 1) { return 0; } if (text[i] == '\n') { i++; } if (text[i] != '\0') { return 0; } *out = value; return 1; } int add_session(struct Session sessions[], int *count, int minutes) { if (sessions == NULL || count == NULL || *count < 0 || *count >= SESSION_CAPACITY || minutes < 1 || minutes > MAX_MINUTES) { return 0; } sessions[*count].minutes = minutes; (*count)++; return 1; } int total_minutes(const struct Session sessions[], int count) { int total = 0; for (int i = 0; i < count; i++) { total += sessions[i].minutes; } return total; } #ifndef REPORT_H #define REPORT_H #define SESSION_CAPACITY 8 #define MAX_MINUTES 180 struct Session { int minutes; }; /* On failure, leave *out unchanged. */ int parse_minutes(const char *text, int *out); /* Caller supplies count initialized records, 0 <= count <= SESSION_CAPACITY. */ int total_minutes(const struct Session sessions[], int count); /* Returns 0 without changing storage when invalid or full. */ int add_session(struct Session sessions[], int *count, int minutes); #endif 25 10 bad 180 0
Check your prediction
Text
Sessions: 3
Total: 215 minutes
Rejected: 2

Now run the acceptance cases from the brief. Empty the input box, then try nine lines containing 1. Finally insert a line of 40 digits followed by a valid 25: the long line should be rejected once and the valid line still accepted.

Was this article helpful?

Your response is saved on this device.