bhylu.com

Advertisements

C++ Output Streams

Combine text and values with stream insertion and choose a display precision deliberately.

How it works

std::cout is a standard output stream. Insertion operators format values according to their types and stream state. Formatting manipulators such as fixed and setprecision change how later floating values appear on that stream. Displaying two decimal places does not make binary floating arithmetic exact. Newline characters finish lines without necessarily flushing the stream; std::endl also requests a flush and is usually unnecessary for each line in a batch report.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror output-streams.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · output-streams.cpp

#include <iostream>
#include <iomanip>

int main() {
    int stops{3};
    double distance_km{8.25};
    std::cout << "Stops: " << stops << '\n';
    std::cout << std::fixed << std::setprecision(2) << "Distance: " << distance_km << " km\n";
    std::cout << "Driver note: \"rear gate\"\n";
}

Expected result

Stops: 3
Distance: 8.25 km
Driver note: "rear gate"

The stream selects integer and floating formatting from the inserted types, avoiding variadic format mismatches. Escaped double quotes belong inside the string literal; they do not close it. The precision setting persists, so restore it or isolate formatting when another part of a larger report needs a different style.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.