Skip to content
C++ Basics: Reject Partial Integer Input with std::from_chars

C++ Basics: Reject Partial Integer Input with std::from_chars

November 2, 2026

Parsing a prefix is not the same as validating an entire field. std::from_chars can successfully read the 12 in 12ms. Check where conversion stopped before accepting the input.

Prepare a scratch directory

Tested on Linux x86_64 with GCC 14.2.0. Install G++ and its C++ standard-library development files, and make g++ available on PATH. You also need Bash, a text editor, and mktemp, rm, and rmdir. No third-party C++ library is required.

Keep the same terminal open. Stop if setup fails, before saving the source:

start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1

Run the example

Save this as from-chars-strict-integers-demo.cpp:

#include <charconv>
#include <iostream>
#include <optional>
#include <string_view>
#include <system_error>

std::optional<int> parse_integer(std::string_view text)
{
    if (text.empty()) {
        return std::nullopt;
    }
    int value = 0;
    const char* end = text.data() + text.size();
    const auto conversion = std::from_chars(text.data(), end, value);
    if (conversion.ec != std::errc{} || conversion.ptr != end) {
        return std::nullopt;
    }
    return value;
}

int main()
{
    for (const auto text : {"42", "-7", "12ms", " 8", "+9", ""}) {
        const auto value = parse_integer(text);
        std::cout << '[' << text << "]: ";
        if (value) {
            std::cout << *value << '\n';
        } else {
            std::cout << "rejected\n";
        }
    }
}

Compile and run it. The second command runs only after compilation succeeds:

g++ -std=c++20 -Wall -Wextra -Werror -pedantic from-chars-strict-integers-demo.cpp -o from-chars-strict-integers-demo &&
./from-chars-strict-integers-demo

Observed output:

[42]: 42
[-7]: -7
[12ms]: rejected
[ 8]: rejected
[+9]: rejected
[]: rejected

Read the result

The helper rejects empty input before pointer arithmetic. A successful conversion must report no error and consume the entire view. Thus 12ms is rejected despite its valid numeric prefix. Leading whitespace and a leading plus sign are not accepted by this integer conversion; a minus sign is accepted for the signed int target.

Apply it carefully

Choose the destination type and numeric base deliberately. A value outside the destination range produces an error and is rejected by this helper. If your format allows spaces or separators, validate and normalize them explicitly rather than silently assuming locale-aware behavior. The optional result intentionally combines syntax and range failures; preserve the error code if callers need to distinguish them.

The C++ working draft specifies the relevant library behavior. The example uses interfaces available in C++20; the current working draft also describes later additions.

Clean up

Remove only the source and executable created here, then return to the starting directory:

rm -- from-chars-strict-integers-demo.cpp from-chars-strict-integers-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directory

If the directory is not empty, inspect the remaining contents before removing anything else.

Acknowledgements

This post was created with assistance from AI.

Last updated on