Lesson contents

C++ — Validating integers with from_chars

C++ std::from_chars reports a conversion status and the position where parsing stopped. Inspect both to distinguish a complete integer from a token such as 3x.

A simple example

Turn text into a number

  1. Start with "2"
  2. Do this Read an integer, add 1
  3. Result 3
The conversion produces the number 2. Adding one now gives 3.
lesson.cpp
#include <iostream>
#include <charconv>
#include <string_view>

int main() {
    std::string_view text = "2";
    int n = 0;
    auto end = text.data() + text.size();
    auto result = std::from_chars(text.data(), end, n);
    if (result.ec == std::errc{} && result.ptr == end)
        std::cout << n + 1 << '\n';
}
Output
3
Advertisements

Validate a seat number

from_chars reports conversion errors separately from the pointer to the first unconsumed character. Check both to reject tokens such as 3x. optional makes absence explicit without reserving a seat number.

Seat 3: Accept. Seat 0: Out of range. Seat x: Invalid number.
Validate a seat request

A minibus has seats numbered 1 to 8. A passenger entering 3 can be assigned that seat. Zero is numeric but outside the seating plan, and x cannot be read as a whole seat number.

Run the example

C++17. Run these commands from the directory containing the example. Use a Unix-style shell.

c++ -std=c++17 lesson.cpp -o lesson
./lesson
lesson.cpp
#include <iostream>
#include <charconv>
#include <optional>
#include <string_view>
#include <system_error>

std::optional<int> seatNumber(std::string_view text) {
    int n = 0;
    const char* end = text.data() + text.size();
    const auto parsed = std::from_chars(text.data(), end, n);
    if (parsed.ec != std::errc{} || parsed.ptr != end || n < 1 || n > 8) {
        return std::nullopt;
    }
    return n;
}

int main() {
    for (const auto text : {"3", "0", "x"}) {
        if (auto seat = seatNumber(text)) std::cout << *seat << '\n';
        else std::cout << "invalid\n";
    }
    return 0;
}
Output
3
invalid
invalid

Only whole-number seat labels from 1 through 8 are accepted. The text 3 passes both checks. Zero parses but is outside the range. The letter x does not represent a decimal seat number.

Try it yourself

Predict the results for 8, 9, and an empty string.

Check your answer

Only 8 is accepted. Nine is outside the range and an empty string has no digits. The existing loop can continue after either rejection.

C++ language and library reference

Related tags

  • C++
  • validation
  • errors
  • optional values