C++ Academy · Lesson

String Conversions: to_string and stoi

Convert between strings and numeric types safely with std::to_string, std::stoi and std::stod.

Lesson 4 of 413 steps

String Conversions: to_string and stoi is a free C++ Academy lesson on CoddyKit. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, and your progress syncs across the web and the CoddyKit app. The C++ Academy course includes 4 lessons in total.

Why String Conversions Matter

You constantly need to convert between numbers and text — for user input, configuration files, JSON, URLs, and logs.

std::to_string

std::to_string converts any built-in numeric type to a string. It uses default formatting.

#include <string>

std::string a = std::to_string(42);     // "42"
std::string b = std::to_string(-7);     // "-7"
std::string c = std::to_string(3.14);   // "3.140000"

Default Float Formatting

to_string on a double uses six decimal places. For precise control use std::stringstream with std::fixed and std::setprecision, or std::format in C++20.

std::stoi: String to int

Parse an integer with std::stoi. It skips leading whitespace and stops at the first non-digit.

int n = std::stoi("42");        // 42
int m = std::stoi("  -7abc");   // -7 (stops at 'a')

Reading the Tail Position

Pass a pointer to receive the index where parsing stopped — useful for parsing mixed strings.

std::string s = "42px";
size_t pos;
int n = std::stoi(s, &pos);
std::cout << pos;  // 2  (parsed "42", stopped at 'p')

Stoi Throws on Bad Input

If no digits are found, stoi throws std::invalid_argument. If the number overflows, it throws std::out_of_range.

try {
    int x = std::stoi("not_a_number");
} catch (const std::invalid_argument& e) {
    std::cout << "Parse failed";
}

Base Conversions

The third argument selects the base (2-36). Pass 0 to auto-detect from prefix.

int hex = std::stoi("ff", nullptr, 16);    // 255
int bin = std::stoi("1010", nullptr, 2);   // 10
int auto_detect = std::stoi("0xff", nullptr, 0); // 255

stol stoll stoul stoull

Variants for the other integer types:

  • std::stol — long
  • std::stoll — long long
  • std::stoul — unsigned long
  • std::stoull — unsigned long long

stof stod stold

Floating-point variants for float, double, and long double.

double d = std::stod("3.14159");
float f = std::stof("2.71");

C++17 std::from_chars: No Throw

std::from_chars parses without throwing. It returns a struct with ec (error code) and ptr (parse end position) — preferred in hot loops.

#include <charconv>
std::string s = "42";
int val;
auto result = std::from_chars(s.data(), s.data() + s.size(), val);
if (result.ec == std::errc{}) {
    // success
}

C++17 std::to_chars: No Allocation

The reverse of from_chars — write a number into a buffer without allocating. The fastest available conversion in the standard library.

Quick Check

Which exception does std::stoi("abc") throw?

Recap

std::to_string converts numbers to strings; std::stoi and friends parse strings to numbers. Both throw on failure — use std::from_chars for noexcept high-performance parsing.

Free to start

Learn C++ with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “String Conversions: to_string and stoi” lesson free?

Yes — any 3 lessons of the C++ Academy learning path, including “String Conversions: to_string and stoi”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The C++ Academy course includes 4 lessons in total.

What will I learn in “String Conversions: to_string and stoi”?

Convert between strings and numeric types safely with std::to_string, std::stoi and std::stod. You practise C++ Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C++ Academy?

No prior experience is required. C++ Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.

How long does the “String Conversions: to_string and stoi” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C++ Academy lesson?

Yes. Every C++ Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. std::string vs C-Style Char Arrays
  2. String Operations: concat substr find replace
  3. String Stream stringstream for Parsing
  4. String Conversions: to_string and stoi
← Back to C++ Academy