bhylu.com

Advertisements

C++ String Streams

Parse one controlled text record and reject leftover fields instead of silently accepting a partial line.

How it works

An istringstream gives stream extraction semantics to an owned text fixture. Formatted extraction skips leading whitespace and sets failure state when a conversion cannot complete. A successful first field does not prove that an entire record is valid. This lab grammar is one stop token followed by a parcel count, separated by whitespace; stop names with spaces are deliberately outside it. Check required fields, domain limits and trailing content before accepting the record.

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 stream-parsing.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 · stream-parsing.cpp

#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::istringstream input{"Quay 12"};
    std::string stop; int count{}; std::string extra;
    if (!(input >> stop >> count) || count < 0 || count > 1000 || (input >> extra)) { return 1; }
    std::cout << stop << ": " << count << " parcels\n";
}

Expected result

Quay: 12 parcels

The fixture contains exactly two fields, so the attempted extra extraction reaches end of stream and the record is accepted. A production grammar may need to distinguish an I/O error from a clean end; a stringstream fixture isolates parsing from external read failures. For exact no-whitespace numeric syntax, from_chars offers a clearer contract than formatted extraction.

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.