C++ Integer Parsing with std::from_chars
Reject trailing text and values outside the delivery domain without depending on locale-sensitive conversion.
How it works
std::from_chars parses a bounded character range and reports both an error code and the stopping pointer. It does not skip leading whitespace, unlike many stream conversions. Check the error and require complete consumption when the input grammar is exactly one decimal number. The parser below then enforces a parcel count from zero through one thousand. Conversion and domain validation are separate layers, and an optional result keeps a valid zero distinct from rejection.
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 parse-integers.cpp -o lessonOn 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
#include <iostream>
#include <charconv>
#include <optional>
#include <string_view>
#include <system_error>
std::optional<int> parse_count(std::string_view text) {
if (text.empty()) { return std::nullopt; }
int value{};
auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), value);
if (error != std::errc{} || end != text.data() + text.size() || value < 0 || value > 1000) { return std::nullopt; }
return value;
}
int main() {
std::cout << "Accepted: " << parse_count("42").value_or(-1) << '\n';
std::cout << "Junk accepted: " << parse_count("42kg").has_value() << '\n';
}
Expected result
Accepted: 42
Junk accepted: 0
The successful fixture consumes both digits. The second stops before the letters and is rejected despite having parsed a numeric prefix. A default-constructed empty string_view may have a null data pointer, so the helper should reject empty input before constructing its pointer range. This makes the empty-case precondition explicit instead of relying on library tolerance.
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.