Site Guide

Find your way around the Engineering Club.

Know what you need? Search for a component, concept or project.

Around the site

Start

Labs

TestingExperimental

Build

Club

LearnExperimental

Go a little deeper

Entry points to larger collections. Use Search for individual records.

Learning paths & reference

Inside PiCrawlerExperimental

Inside Inventory

← C++ Worked Programs

Learn / Worked program

Measurement File Analyzer

A new class example with a real invariant

IntermediateDesktop C++17 · runnable source

What you will learn

The complete source

main.cpp

main.cpp
#include <cmath>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>

class MeasurementLog {
public:
    void add(double value) {
        if (!std::isfinite(value) || std::abs(value) > 1e6) {
            throw std::invalid_argument("Measurement must be finite and within +/-1e6.");
        }
        if (values_.size() == 10000) throw std::length_error("Measurement limit is 10000.");
        values_.push_back(value);
    }
    std::size_t count() const { return values_.size(); }
    double mean() const {
        if (values_.empty()) throw std::logic_error("No measurements to average.");
        double sum = 0.0;
        for (double value : values_) sum += value;
        return sum / static_cast<double>(values_.size());
    }
private:
    std::vector<double> values_;
};

int main(int argc, char* argv[]) {
    if (argc != 2) { std::cerr << "Usage: program input-file\n"; return 1; }
    std::ifstream input(argv[1]);
    if (!input) { std::cerr << "Cannot open input file.\n"; return 1; }
    MeasurementLog log;
    std::string line;
    std::size_t lineNumber = 0;
    try {
        while (std::getline(input, line)) {
            ++lineNumber;
            std::istringstream row(line);
            double value = 0.0;
            char extra = '\0';
            if (!(row >> value) || row >> extra) throw std::invalid_argument("Expected one number per line.");
            log.add(value);
        }
        if (input.bad()) throw std::runtime_error("Read failed before end of file.");
        std::cout << "Count: " << log.count() << '\n' << std::fixed << std::setprecision(6)
                  << "Mean: " << log.mean() << '\n';
    } catch (const std::exception& error) {
        std::cerr << "At or after line " << lineNumber << ": " << error.what() << '\n';
        return 1;
    }
}
Source integrity

SHA-256 9923b500cbcab80ca06b27972e866684c248256a577a9153da204d52f9242bce. Display, copy and approved download use the same source.

What it does and why it was selected

The user-source archive has no strong class-and-file example suitable for publication. Instructor files identify those topics but cannot be republished. This independently authored Engineering Club program reads one measurement per line and uses a class to protect a meaningful invariant: only finite, bounded measurements enter its collection.

Actual execution

main requires one input-file argument, opens ifstream and rejects a failed open. A local MeasurementLog begins with an empty private vector. Each getline increments lineNumber and is parsed through a new istringstream. A line must contain exactly one number plus optional whitespace. log.add checks numerical and count limits before push_back. After the read loop, main checks input.bad to distinguish an I/O failure from ordinary EOF. mean refuses an empty log and otherwise sums stored values and divides by the count converted to double. The supplied 10,12,14 fixture produces count 3 and mean 12.000000.

Mathematical or state model

The output is an arithmetic mean of equally weighted scalar readings. No unit is assumed in the source, so all values in one file must use a common unit and represent comparable measurements. Averaging voltages and temperatures together would be meaningless even if the parser accepts both numbers. The example intentionally does not calculate uncertainty, precision of a measurement instrument, calibration correction or sample standard deviation.

Design and C++ mechanics

private values_ blocks callers from inserting arbitrary numbers without validation. add is a member function that controls mutation; count and mean are const queries, so they cannot change the vector through this interface. The vector owns its elements, and automatic object lifetime releases storage at scope exit. The ifstream also closes through its destructor, including exception paths. This is a reason to use a class rather than a mere set of public fields: callers need to preserve a state invariant, not simply group unrelated values.

Historical differences and limits

The sum is bounded by 10000 measurements each with magnitude at most 1e6, comfortably finite in double arithmetic, but finite is not the same as numerically optimal. Severe cancellation can still reduce mean accuracy. Blank lines are treated as invalid records rather than skipped; changing that policy changes line semantics and should be documented. The exception boundary prints the line where parsing or insertion failed. The program reads a file supplied by the user and writes no output file, so no historical input is copied or overwritten.

Useful extensions

Add a unit label in a defined file format and reject inconsistent units. For large streams, a running mean can avoid storing every sample; compare the ownership and later-analysis tradeoff before removing the vector. If adding a standard deviation, define population versus sample conventions and use a numerically stable method rather than subtracting nearly equal sums of squares.

Source-linked explanations

Follow each line reference to its marked source region. The explanations below are bound to the reviewed source hash and preserve the supplied teaching layers.

Private storage gives add control over validity

main.cpp, lines 10–33 →

values_ is private, so main cannot push arbitrary numbers into the vector.

Technical explanation
values_ is private, so main cannot push arbitrary numbers into the vector. add rejects nonfinite or excessive values and a full log before push_back changes size. mean refuses an empty collection. const count and mean observe without allowing ordinary mutation through those member functions.
Syntax
const count and mean observe without allowing ordinary mutation through those member functions.
Effect on the program
const count and mean observe without allowing ordinary mutation through those member functions.
Common mistake
A class whose public vector can be edited directly would not enforce the stated measurement invariant.

classesencapsulationvectors

Compute an equal-weight mean with a nonempty precondition

main.cpp, lines 20–26 →

The empty check runs before division.

Technical explanation
The empty check runs before division. Range-for copies each small double and accumulates sum. size() returns an unsigned count, explicitly converted to double for division. The supported count and magnitude bounds keep the sum finite, although they do not eliminate cancellation error.
Syntax
The supported count and magnitude bounds keep the sum finite, although they do not eliminate cancellation error.
Effect on the program
The supported count and magnitude bounds keep the sum finite, although they do not eliminate cancellation error.
Common mistake
Empty-file input must not divide by zero. Integer division of an integer sum by a count would lose the fractional mean.

functionsvectorsfloating point

File lifetime is automatic

main.cpp, lines 32–35 →

Opening the argument path creates an input stream that owns the file handle.

Technical explanation
Opening the argument path creates an input stream that owns the file handle. Testing !input detects a failed open before any reads. The object closes through its destructor on normal return or exception unwinding; explicit close is unnecessary here.
Syntax
The object closes through its destructor on normal return or exception unwinding; explicit close is unnecessary here.
Effect on the program
The object closes through its destructor on normal return or exception unwinding; explicit close is unnecessary here.
Common mistake
A compiled program is not evidence that the requested file exists or that reading succeeded.

file ioconstructors lifetime

Parse records before changing the collection

main.cpp, lines 38–45 →

Each line gets a fresh istringstream, then exactly one double is required.

Technical explanation
Each line gets a fresh istringstream, then exactly one double is required. A successful extra-character extraction means non-whitespace trailing data and triggers an exception. Only a valid parsed value reaches log.add, so rejected records cannot pollute the vector. lineNumber identifies the current record in the error message.
Syntax
lineNumber identifies the current record in the error message.
Effect on the program
lineNumber identifies the current record in the error message.
Common mistake
Silently skipping bad lines changes the dataset and could bias an average. This version rejects them explicitly.

stringsfile ioexceptions

One error boundary covers parsing and invariants

main.cpp, lines 49–53 →

The const reference catches standard exception subclasses without copying or slicing the exception object.

Technical explanation
The const reference catches standard exception subclasses without copying or slicing the exception object. what() provides the diagnostic text from the throw site. Returning 1 makes failure observable to a terminal or test runner. Already-constructed automatic objects are destroyed as control leaves main.
Syntax
Already-constructed automatic objects are destroyed as control leaves main.
Effect on the program
Already-constructed automatic objects are destroyed as control leaves main.
Common mistake
Catching an exception and then printing a successful mean would falsely present an incomplete dataset as a completed analysis.

exceptionsreferences

Recorded input and output

Captured from the compiled canonical program in the supplied verification package. These are recorded terminal sessions, not an interactive browser runner.

Sample run

Arguments
sample-measurements.txt
Recorded exit status
0

Program input

No standard input.

Program output

Count: 3
Mean: 12.000000
6 more recorded behavior and error cases
empty file
Arguments
empty.txt
Recorded exit status
1

Program input

No standard input.

Program output

Count: 0
Mean: 

Error output

At or after line 0: No measurements to average.
bad file
Arguments
malformed.txt
Recorded exit status
1

Program input

No standard input.

Program output

No standard output.

Error output

At or after line 2: Expected one number per line.
blank line
Arguments
blank.txt
Recorded exit status
1

Program input

No standard input.

Program output

No standard output.

Error output

At or after line 2: Expected one number per line.
missing file
Arguments
missing.txt
Recorded exit status
1

Program input

No standard input.

Program output

No standard output.

Error output

Cannot open input file.
missing argument
Arguments
None
Recorded exit status
1

Program input

No standard input.

Program output

No standard output.

Error output

Usage: program input-file
huge value
Arguments
huge.txt
Recorded exit status
1

Program input

No standard input.

Program output

No standard output.

Error output

At or after line 1: Measurement must be finite and within +/-1e6.

Build and run

From this folder, with a configured C++17 compiler:

sh
g++ -std=c++17 -Wall -Wextra -Wpedantic main.cpp -o program
./program sample-measurements.txt

On Windows GCC, build with -o program.exe and use .\program.exe sample-measurements.txt. These are desktop examples; VS Code is an editor, the compiler builds an executable, and the terminal runs it.

Windows run command from the supplied metadata: .\program.exe sample-measurements.txt.

Desktop compiler setup and platform limits. How headers and translation units fit together.

Supporting material

Sample measurement input

sample-measurements.txt
10
12
14
Source integrity

SHA-256 7eaaffcc93efd54f01527b25a6cae491c4aadd6de533fbce8fe84607fde8ddd6. Display, copy and approved download use the same source.

Verification and provenance

  • Source inspected
  • Compile verified
  • Warning reviewed
  • Behavior verified
  • Sanitizer checked

Supplied evidence: 7 recorded behavior/error cases and 7 address/undefined-behavior sanitizer cases for this exact source. These are tested cases, not an exhaustive correctness claim.

Recorded compiler: g++ (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0.

LeakSanitizer: disabled because unavailable under runtime tracing. Windows/MSVC and macOS execution are not certified by this evidence.

Source origin and publication treatment

New engineering club example

Independently authored Engineering Club class/file example. Historical source links document conceptual inspiration only, not copied source or original authorship.

New or rewritten source, limited sanitized historical excerpts when useful

No new license is asserted by this publication.