IntermediateLesson 15 of 205 min read

Project: A Log Analyser for the Weather Station

Build a program that parses a log of timestamped sensor readings, validates every line, computes per-sensor statistics and a daily summary, and verify the report against an independent Python implementation.

In this lesson you will

  • Parse text lines safely
  • Validate and report bad lines
  • Group readings per sensor
  • Verify a report independently

About 28 minutes

The day’s log, read by a program

Elena’s station writes one line for each reading: a time, a sensor name and a value. Real logs contain mistakes, such as a missing value, text where a number should be, and a reading that is physically impossible. The program must read all of it, reject bad lines with a reason, keep the good ones, and report per-sensor statistics. This project joins strings, streams, containers, algorithms and error handling from the previous lessons.

Step Technique
Split a line std::istringstream
Convert text to a number std::from_chars or stod with checks
Validate Field count, number format and range -50 to 60
Group std::map from sensor name to vector of values
Report Count, mean, min, max per sensor

Parsing numbers is where programs go wrong. The function std::stod throws an exception for text that is not a number, but it accepts text with trailing junk, such as 12.5abc, and reads only the leading part. The safer approach is std::from_chars from , which reports exactly how much text it consumed, and the program checks that all of it was used. The input lines in this lesson are built into the program, so that it is self-contained, and three of the twelve lines are bad on purpose.

#include <algorithm>
#include <charconv>
#include <format>
#include <iostream>
#include <map>
#include <numeric>
#include <sstream>
#include <string>
#include <vector>

struct Parsed { bool ok; std::string sensor; double value; std::string why; };

Parsed parse_line(const std::string& line) {
    std::istringstream in(line);
    std::string time, sensor, num;
    if (!(in >> time >> sensor >> num)) return {false, "", 0, "wrong field count"};
    double v = 0;
    auto [end, ec] = std::from_chars(num.data(), num.data() + num.size(), v);
    if (ec != std::errc() || end != num.data() + num.size()) return {false, "", 0, "not a number"};
    if (v < -50 || v > 60) return {false, "", 0, "out of range"};
    return {true, sensor, v, ""};
}

int main() {
    std::vector<std::string> log{"06:00 roof 14.2", "06:30 roof 14.8", "06:30 garden 12.1", "07:00 roof 15.9", "07:00 garden oops", "07:30 garden 13.4", "08:00 roof", "08:00 garden 15.0", "08:30 roof 18.6", "09:00 shed 9.5", "09:00 garden 99.9", "09:30 roof 21.3"};
    std::map<std::string, std::vector<double>> by_sensor;
    std::vector<std::string> problems;
    for (std::size_t i = 0; i < log.size(); ++i) {
        Parsed p = parse_line(log[i]);
        if (p.ok) by_sensor[p.sensor].push_back(p.value);
        else problems.push_back(std::format("line {}: {}", i + 1, p.why));
    }
    std::size_t good = 0;
    for (const auto& [s, v] : by_sensor) good += v.size();
    std::cout << "lines: " << log.size() << ", valid: " << good << ", rejected: " << problems.size() << "\n";
    for (const auto& p : problems) std::cout << "  " << p << "\n";
    std::cout << std::format("{:<8}{:>6}{:>9}{:>8}{:>8}\n", "sensor", "count", "mean", "min", "max");
    for (const auto& [s, v] : by_sensor) {
        double mean = std::accumulate(v.begin(), v.end(), 0.0) / v.size();
        auto [mn, mx] = std::minmax_element(v.begin(), v.end());
        std::cout << std::format("{:<8}{:>6}{:>9.3f}{:>8.1f}{:>8.1f}\n", s, v.size(), mean, *mn, *mx);
    }
    auto warmest = std::max_element(by_sensor.begin(), by_sensor.end(), [](const auto& a, const auto& b) {
        return *std::max_element(a.second.begin(), a.second.end()) < *std::max_element(b.second.begin(), b.second.end()); });
    std::cout << "highest single reading came from: " << warmest->first << "\n";
}
lines: 12, valid: 9, rejected: 3
  line 5: not a number
  line 7: wrong field count
  line 11: out of range
sensor   count     mean     min     max
garden       3   13.500    12.1    15.0
roof         5   16.960    14.2    21.3
shed         1    9.500     9.5     9.5
highest single reading came from: roof

The program read 12 lines, accepted 9 and rejected 3, giving each rejected line a number and a reason: line 5: not a number; line 7: wrong field count; line 11: out of range. The text “oops” is not a number, the line with a missing value has the wrong number of fields, and 99.9 degrees is outside the plausible range of -50 to 60. The table gives each sensor’s count, mean, minimum and maximum, built from the map of vectors, and the highest single reading came from the roof sensor. Because each bad line is reported and skipped, one wrong value does not spoil the day’s statistics.

To verify the report, the course implemented the same rules independently in Python, with its own parsing, range check and statistics. It rejected the same lines, 5 (not a number), 7 (wrong field count), 11 (out of range), and its per-sensor results were garden: n=3, mean=13.500, min=12.1, max=15.0, roof: n=5, mean=16.960, min=14.2, max=21.3, shed: n=1, mean=9.500, min=9.5, max=9.5, identical to the C++ table. The highest reading also came from roof. Two separate implementations agreeing on every figure is the best evidence that a program does what you think.

Check by hand: the roof has 5 valid readings, 14.2, 14.8, 15.9, 18.6, 21.3, which add up to 84.8 and give the mean 16.960 in the table. In total 9 of the 12 lines were valid, and the 3 rejected lines were lines 5, 7, 11.

Parse numbers with care

stod accepts trailing junk and throws on failure. from_chars tells you how much it consumed, and the program must check that the whole token was used.

Separate parsing from reporting

The parse_line function returns a small struct, and the report works on the clean data. You can then test parsing with a list of tricky lines and no files.

About this course

Every program in this lesson was compiled with GCC 13 using -std=c++20 -Wall -Wextra and run while the course was written. C++ has a new standard every three years and compilers differ in what they support, so check your compiler’s documentation and cppreference.com for the current state. std::from_chars for double needs a standard library with floating point support, which GCC 11 and later have.

Practice

Add the time of the maximum reading for each sensor. Read the log from a file named on the command line, using std::ifstream and std::getline. Write the rejected lines to a second file and check one total by hand.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What should the analyser do with a bad line?

  1. Stop the program
  2. Ignore it silently
  3. Change it
  4. Report it with a reason and continue

Bad data is normal.

Why use from_chars instead of stod?

  1. It is shorter
  2. It is required
  3. It reports how much text was consumed
  4. It rounds

stod accepts trailing junk.

Why separate parsing from reporting?

  1. It is faster
  2. C++ requires it
  3. Each can be tested alone
  4. It saves memory

Clean data in, report out.

How was the report verified?

  1. By reading it
  2. By an independent Python implementation
  3. By running it twice
  4. It was not

Every number matched.

What does the map from sensor to vector give you?

  1. A sorted list of lines
  2. All values of each sensor grouped together
  3. A file
  4. A thread

Statistics per sensor.

Summary

  • A log analyser parses, validates, groups and reports.
  • Reject bad lines with a reason and carry on.
  • from_chars parses numbers safely.
  • An independent implementation verifies the numbers.

Next lesson

Lesson 16 starts the Advanced level with error handling and testing.

Questions

Should I use exceptions for bad lines?

You can, but bad input is expected, so returning a result struct, as here, is clearer and faster than throwing.

How do I read a real file?

Open a std::ifstream, call std::getline in a loop and pass each line to the same parse_line function.

Is the range check physical or logical?

It is a sanity check chosen for this station. Choose limits that fit your sensors, and make them configurable.

Progress is saved in this browser.