Project 9.06 Section 9 ⚡ Embedded Relevance: Core <iomanip> setw setprecision Formatting Statistical Reports

9.06 Formatted Stream Manipulators (<iomanip>), Fixed-Width Alignments & Sensor Summary Reports

Executive Summary: Generating formatted tabular text reports using (std::setw, std::setprecision, std::fixed). We analyze table column alignment, computing running averages/min/max statistics, and generating ASCII telemetry summary logs for embedded serial terminals.

💻 1. Annotated Source Code

#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;

int main() {
	ifstream infile("salaries.txt");

	if (!infile) {
		cerr << "Error opening file.  Aborting..." << endl;
		return 1;
	}

	double salary;
	int employeeCount = 0;
	double totalSalary = 0.0;
	int highEarners = 0;

	while (infile >> salary) {
		if (salary < 0 || salary > 1000000) {
			//skip invalid data
			continue;
		}

		employeeCount++;
		totalSalary += salary;

		if (salary > 100000) {
			highEarners++;
		}
	}//end while

	infile.close();

	double averageSalary = (employeeCount > 0) ? totalSalary / employeeCount : 0.0;

	cout << fixed << showpoint << setprecision(2);
	cout << "Employee Salary Report" << endl;
	cout << "-------------------------------" << endl;
	cout << "Total Employees:               " << employeeCount << endl;
	cout << "Total Payroll:                 $" << totalSalary << endl;
	cout << "Average Salary:                $" << averageSalary << endl;
	cout << "Over $100,000 Earners:         " << highEarners << endl;

	return 0;
}
55000
72000
98000
121000
45000
105000
86000
34000
145000
99999

📐 2. Architecture & UML Class Model

📐 Employee Salary File Parser & Aggregate Report Model
+ Public - Private # Protected
<<struct>> EmployeeRecord Payroll Record
+employeeName : std::string
+baseSalaryCents : int64_t
+taxWithheldCents : int64_t
+getNetSalaryCents() : int64_t const
<<compilation-unit>> SalaryReportGenerator Payroll Engine
-employees : std::vector<EmployeeRecord>
+loadSalaries(path: const char*) : void
+printFinancialSummary() : void const
🔗 Architectural Relationships & Hierarchy
SalaryReportGenerator ◆── aggregates ◆── EmployeeRecord

📚 3. Core C++ Concepts Deep-Dive

1. Formatted Stream Manipulators (<iomanip>)

  • std::setw(N): Sets field width for the next item.
  • std::setprecision(N): Sets decimal precision.
  • std::fixed: Formats floating-point numbers with fixed decimal notation.

⚡ 4. Embedded Systems & Hardware Reality

1. Embedded ASCII Telemetry Tables

In satellite and drone serial consoles, formatted ASCII tables provide human-readable sensor health summaries over radio telemetry links.

💡 5. Production-Ready Embedded Refactoring

Lightweight string buffer table formatter:

💡 Production-Ready Refactor
#include <cstdint>
#include <cstdio>

struct SensorReport {
    uint8_t  id;
    int16_t  temp_c;
    uint16_t voltage_mv;
};

// Compact snprintf formatting: 0 <iomanip> Flash bloat!
void formatReportLine(const SensorReport& r, char* out_buf, size_t buf_len) noexcept {
    snprintf(out_buf, buf_len, "| ID: %02u | Temp: %+03d C | V: %04u mV |\r\n",
             r.id, r.temp_c, r.voltage_mv);
}

📝 Knowledge Verification Quiz

Test your understanding of the C++ concepts and embedded microcontroller trade-offs covered in this guide. Click any option for instant feedback.

Q1. Which header file provides stream manipulators like std::setw, std::setprecision, and std::setfill?
A <iomanip>
B <iostream>
C <stdlib.h>
D <sstream>
Detailed Explanation: <iomanip> contains formatting manipulators for parameterized stream formatting.
Q2. Why is 'snprintf()' often preferred over '<iomanip>' for formatting text in small microcontroller firmware?
A 'snprintf()' is extremely compact in Flash ROM, avoids linking heavy C++ locale machinery, and prevents buffer overflows with explicit length bounds
B 'snprintf()' is faster than CPU clock speed
C 'snprintf()' only works on 8-bit AVR
D '<iomanip>' cannot output numbers
Detailed Explanation: snprintf() provides bounded, format-string-based output with minimal Flash footprint compared to heavy C++ streams.
Q3. What is the scope of 'std::setw(10)' when applied to a stream (cout << setw(10) << a << b;)?
A It applies ONLY to the very next single item ('a'); subsequent items ('b') revert to default formatting
B It applies permanently to all future items
C It formats the entire line
D It sets width for the next 10 items
Detailed Explanation: std::setw is non-sticky: it affects only the immediately following output token.
Q4. How do you calculate running minimum and maximum values across a stream of numbers in $O(1)$ memory?
A Initialize min = +INFINITY, max = -INFINITY, and update with std::min() / std::max() on each element
B Store all elements in a sorted array
C Use a hash table
D Re-read the file from the start on every item
Detailed Explanation: Tracking running min/max requires only two scalar variables updated on each iteration ($O(1)$ space).