Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 171 ยท Strings

Converting Between Strings and Numbers

Convert between strings and numbers in C++ - std::to_string, stoi and stod with their exceptions, fast from_chars and to_chars, std::format, and safe parsing helpers.

Text comes into programs as characters: command-line arguments, lines of a CSV file, JSON fields, a number typed into the Input box. Before you can do arithmetic with "42", you must turn it into the integer 42. Going the other way, numbers must become text before you can put them in a file name, a message or a network packet.

C++ gives you three generations of tools for this, and choosing well matters. std::to_string and std::stoi/std::stod (C++11) are easy and throw exceptions on bad input. std::from_chars and std::to_chars (C++17, header <charconv>) are the fastest conversions in the language, never allocate, never throw and ignore the locale. std::format (C++20) is the most flexible way to turn numbers into text. In this lesson you'll learn all three, the surprising things each one accepts, and how to write a parsing helper that rejects every kind of bad input.

Numbers to strings: std::to_string

std::to_string (header <string>) has overloads for every arithmetic type and returns a new std::string:

C++ std::to_string and its quirks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

For integers, std::to_string is perfect. For floating-point values it behaves like C's %f: always six decimal places, so 3.14 becomes "3.140000" and 1e-7 collapses to "0.000000". That's rarely what you want. C++26 changes to_string for floating point to produce the same shortest form as std::format("{}"); until your compiler and standard mode have that, use std::format for doubles.

Converting with std::format("{}", x) (or with a spec like {:.2f}) works for every type, as you saw in Formatting with std::format and std::print. It's the best default for building messages and file names. Use std::to_chars (below) when speed matters or you need to write into an existing buffer.

Strings to numbers: the sto* family

The functions in <string> that parse numbers are named after the type they return:

Function Returns Function Returns
std::stoi int std::stoul unsigned long
std::stol long std::stoull unsigned long long
std::stoll long long std::stof float
std::stod / std::stold double / long double

The integer versions have the signature stoi(const std::string& str, std::size_t* pos = nullptr, int base = 10). They:

  1. skip leading whitespace,
  2. accept an optional + or - sign,
  3. read as many digits as they can,
  4. stop at the first character that doesn't fit and return what they have,
  5. write the number of characters used into *pos, if you pass a pointer.

They report failure with exceptions from <stdexcept>: std::invalid_argument when no digits at all could be read, and std::out_of_range when the value doesn't fit in the result type.

C++ stoi, stod and their exceptions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Notice the danger in the middle: "42 apples" and "3.99" don't throw. They quietly succeed with a partial value. If you're validating input, that's almost never acceptable. Use the pos argument to check that the whole string was consumed:

C++
int parse_whole_int(const std::string& text) {
    std::size_t used = 0;
    int value = std::stoi(text, &used);         // may throw
    if (used != text.size()) {
        throw std::invalid_argument("trailing characters in '" + text + "'");
    }
    return value;
}

std::stoul("-1") doesn't fail. The unsigned versions accept a minus sign and negate the result in unsigned arithmetic, so "-1" becomes 18446744073709551615. If negative input is an error, check for a leading - yourself, or parse into a signed type and compare.

A few more things to know about the sto* functions:

  • They take const std::string&, not a std::string_view, so parsing a view means copying it into a temporary string first.
  • They follow the C locale for floating point. In a program that switched to, say, a German locale, std::stod("2.5") could stop at the dot. Web services and file parsers should not depend on that.
  • Exceptions are expensive when bad input is common, for example when scanning a big file where many fields aren't numbers.

There's also the C heritage: std::atoi, std::atof and std::strtol from <cstdlib>. Avoid atoi: it returns 0 for both "0" and "banana", so you can't detect errors at all.

std::from_chars: fast, strict, no exceptions

std::from_chars (header <charconv>) parses a number from a range of characters given as two pointers, [first, last). It returns a small struct, std::from_chars_result, with two members:

  • ptr: a pointer to the first character that wasn't used,
  • ec: a std::errc that is std::errc{} on success, std::errc::invalid_argument if no number was found, or std::errc::result_out_of_range if it didn't fit.

The result goes into a variable you pass by reference. On failure that variable is left unchanged, which makes "parse with a default" trivial.

from_chars is also stricter than stoi. It does not skip whitespace, does not accept a leading +, and does not understand 0x prefixes (you pass the base instead). It never allocates, never throws and never consults the locale, so the same input gives the same answer on every machine. It's typically several times faster than stoi.

C++ Parsing with from_chars

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The spec {:>14?} prints each input in quoted debug form (C++23), so you can see the leading space in " 7". The structured binding auto [ptr, ec] = ... unpacks the result struct; you'll learn more about it in Returning Values. Since from_chars works on any character range, it pairs naturally with std::string_view: you can parse fields straight out of a big buffer without copying them.

A reusable, strict parser

Most programs need the same thing: "give me the number if the entire text is a valid number, otherwise tell me it isn't". from_chars plus std::optional makes that a short template:

C++ A strict parse_number helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Edit the Input box and run again to test your own values. Notice that " 8" is rejected because of the leading spaces, and 4000000000 is too big for int but fine as a double. If you want to allow surrounding whitespace, trim the view first (the trim helper from the string_view lesson does exactly that). std::optional and templates get full lessons later.

std::to_chars: numbers into a buffer

std::to_chars is the reverse: it writes a number as characters into a buffer you provide, and returns a std::to_chars_result with ptr (one past the last character written) and ec (std::errc::value_too_large if the buffer was too small). It doesn't add a null terminator.

For floating-point values without a format argument, it writes the shortest text that converts back to exactly the same value. That round-trip guarantee is what you want for saving numbers in files or JSON. You can also request std::chars_format::fixed, scientific or general, with an optional precision.

C++ Writing numbers with to_chars

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The lambda write is just a shortcut so each line stays readable; Lambda Expressions explains the syntax. Each call reuses the same buffer, so each returned view is only valid until the next call. That's fine here because each line prints immediately.

Characters and digits

Single characters are a special case, and a common source of beginner bugs.

  • The digits '0' to '9' have consecutive character codes, so c - '0' turns a digit character into its value ('7' - '0' is 7), and static_cast<char>('0' + d) goes back.
  • std::to_string('A') is not "A": a char is an integer type, so you get "65". To make a one-character string, use std::string(1, c) or std::string{c}.
  • std::stoi on a single char doesn't compile without first making a string. For one digit, use c - '0' after checking std::isdigit (see Characters and Booleans).
C++
char c = '7';
int digit = c - '0';                    // 7
char back = static_cast<char>('0' + 4); // '4'
std::string one(1, 'A');                // "A"
std::string oops = std::to_string('A'); // "65", probably not what you meant

Which one should you use?

Need Best choice Why
Number โ†’ text for messages, files, UI std::format flexible, precise control, any type
Integer โ†’ std::string, quick and simple std::to_string short and clear
Floating point โ†’ text that reads back exactly std::to_chars or std::format("{}") shortest round-trip form
Text โ†’ number, validating input std::from_chars (wrap it like parse_number) strict, no exceptions, works with views
Text โ†’ number, bad input is truly exceptional std::stoi / std::stod + check pos short; throws on failure
Hot loops parsing large files std::from_chars / std::to_chars fastest, no allocation, no locale
Never std::atoi, std::atof can't report errors

String streams (std::istringstream) can also parse numbers and are handy for splitting lines into mixed fields; they're covered in String Streams.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does std::stoi("12.9 kg") return?

    stoi reads as many digits as it can and stops at the dot. It returns 12 without complaint, which is why you should check the pos argument when validating.
  2. 2. What does std::to_string(2.5) return in C++23?

    For floating point, to_string formats like %f with six decimal places. Use std::format("{}", 2.5) to get "2.5".
  3. 3. Which input does std::from_chars reject for an int, even though std::stoi accepts it?

    from_chars doesn't skip leading whitespace (and doesn't accept a leading +). stoi skips whitespace first.
  4. 4. After int v = 5; auto r = std::from_chars(p, end, v); fails with std::errc::invalid_argument, what is v?

    On failure, from_chars leaves the output variable unchanged. Initializing it with a default before the call gives you a fallback value for free.
  5. 5. What does std::to_string('A') return?

    char is an integer type, so the int overload is chosen and you get the character code. Use std::string(1, 'A') for a one-character string.

Summary

  • std::to_string is great for integers but prints floating point with six fixed decimals (until C++26); prefer std::format for doubles.
  • std::stoi, std::stol, std::stod and friends skip whitespace, stop at the first bad character and throw invalid_argument or out_of_range. Check pos to reject trailing junk; beware stoul("-1").
  • std::from_chars is strict (no whitespace, no +, no prefixes), fast, locale-independent and exception-free; it reports errors in ec, leaves the value unchanged on failure and works with std::string_view.
  • Wrap from_chars in a parse_number helper that also requires ptr == end.
  • std::to_chars writes into your buffer, reports value_too_large, and gives the shortest round-trip form for floating point.
  • For single digits use c - '0'; std::to_string('A') gives "65". Never use atoi.

Next: C-Style Strings and Character Arrays, where you'll meet the null-terminated strings that C APIs still use everywhere.