Call std::to_string(n) from <string>: it returns a std::string for any integer type. To join a number to text, convert it first and then use +: "Level " + std::to_string(n). For padding, hex or a whole message in one call, use C++20's std::format("{:05}", n).
C++ has no implicit int-to-string conversion, and + between a string literal and an int doesn't concatenate: it compiles and does pointer arithmetic instead. The standard library gives you four real ways to turn a number into text. std::to_string (C++11) is the short everyday answer. std::format (C++20) handles width, leading zeros, sign and base, and builds a whole message at once. std::ostringstream is the classic stream approach you'll meet in older code, and std::to_chars (C++17) writes digits into your own buffer with no allocation at all. After those, a section on the mistakes that compile but print the wrong thing, and a table to choose between them. Every example runs on this page: hit Run, then edit the code and run it again.
1std::to_stringRecommended
std::to_string takes any integer type (int, long, long long and their unsigned forms) and returns a new std::string with its decimal digits, a minus sign for negatives, and nothing else: no padding, no thousands separators. That is also the answer to the second most asked question, joining a string and an int. + is defined between two std::strings (or a std::string and a string literal), so convert the number first and the rest is ordinary concatenation. Use += to append to a string you are building in a loop.
#include <iostream> #include <limits> #include <string> int main() { int score = 42; std::string s = std::to_string(score); std::cout << s << " has " << s.size() << " characters\n"; // Every integer type works, negatives and the extremes included std::cout << std::to_string(-17) << '\n'; std::cout << std::to_string(std::numeric_limits<int>::min()) << '\n'; std::cout << std::to_string(9'000'000'000LL) << '\n'; std::cout << std::to_string(4'000'000'000u) << '\n'; // Concatenating: convert the int first, then + joins std::strings std::string name = "Ada"; int level = 7; std::string line = name + " reached level " + std::to_string(level); std::cout << line << '\n'; // += appends to a string you are building std::string csv; for (int n : {3, 14, 15}) { if (!csv.empty()) csv += ','; csv += std::to_string(n); } std::cout << csv << '\n'; }
Output
42 has 2 characters shows the result is a real string with no hidden padding. The smallest int comes out as -2147483648, and the long long and unsigned overloads print 9000000000 and 4000000000 without overflowing (the ' digit separators in the source are C++14 and never reach the output). The concatenated line reads Ada reached level 7, and the loop builds 3,14,15. There is a std::to_wstring twin for std::wstring. Going the other way is converting a string to an int.
2std::format for padding, hex and whole messages
std::format (C++20, header <format>) replaces each {} in its first argument with the next value, so std::format("{}", n) is a drop-in for to_string and a longer pattern builds the whole message without a chain of +. What goes after a colon inside the braces controls the result: a width, < to left-align, 0 for leading zeros, + to always show the sign, and x, X, b or o for hex, upper-case hex, binary or octal, with # adding the 0x or 0b prefix. The pattern is checked when the program compiles, so a typo in it is a build error, not a crash. std::format_to appends to a string you already have.
#include <format> #include <iostream> #include <iterator> #include <string> int main() { int n = 255; std::string s = std::format("{}", n); std::cout << s << '\n'; // Build the whole message in one call instead of a + chain std::string name = "Ada"; int level = 7; std::cout << std::format("{} reached level {}", name, level) << '\n'; // The spec after the colon sets width, padding, sign and base std::cout << std::format("[{:5}] [{:<5}]", 42, 42) << '\n'; std::cout << std::format("{:05}", 42) << '\n'; // leading zeros std::cout << std::format("{:+} {:+}", 42, -42) << '\n'; std::cout << std::format("{:x} {:X} {:#x}", n, n, n) << '\n'; std::cout << std::format("{:b} {:#010b} {:o}", 5, 5, 8) << '\n'; // format_to appends to an existing string std::string id = "user-"; std::format_to(std::back_inserter(id), "{:04}", 7); std::cout << id << '\n'; }
Output
{:5} right-aligns numbers by default, giving [ 42], and {:<5} gives [42 ]. {:05} pads with zeros to 00042, the most common reason people reach past to_string. 255 prints as ff FF 0xff, and in {:#010b} the width of 10 includes the prefix, so 5 becomes 0b00000101. C++23 adds std::println, which formats and prints in one call, but this page compiles as C++20, so the examples pass std::format's result to std::cout. More patterns are in formatting a string.
3std::ostringstream
Before C++11 the standard answer was a string stream: write the number into a std::ostringstream (header <sstream>) with <<, exactly as you would to std::cout, then take the text out with .str(). It still earns its place when you mix many values of different types into one string, or when a type you wrote already has an operator<< but no to_string. Base and padding come from the manipulators in <iomanip>: std::hex, std::setw, std::setfill. Watch out: most of them are sticky and stay in force for every later number on that stream.
#include <iomanip> #include <iostream> #include <sstream> #include <string> int main() { int n = 42; std::ostringstream out; out << n; std::string s = out.str(); std::cout << s << '\n'; // << takes any mix of types, the same way std::cout does std::ostringstream msg; msg << "Ada reached level " << 7 << " with " << 1500 << " points"; std::cout << msg.str() << '\n'; // Manipulators pick the base and padding std::ostringstream fmt; fmt << std::hex << std::uppercase << 255 << ' ' << std::setw(6) << std::setfill('0') << 42; std::cout << fmt.str() << '\n'; // std::hex is sticky: 42 came out as 2A // To reuse a stream, empty it with str(""); the flags stay set, // so switch back to decimal with std::dec fmt.str(""); fmt << std::dec << 42; std::cout << fmt.str() << '\n'; }
Output
The third line is FF 00002A: std::setw(6) applied to the next value only, but std::hex, std::uppercase and the fill character stayed, so 42 was written in hex as well. That stickiness is the classic stream bug. To reuse a stream, str("") empties its text but keeps the flags, which is why the last write needs std::dec to print 42. Each ostringstream also costs more to create than a to_string call, so for one number the shorter functions win.
4std::to_chars: no allocation
std::to_chars (C++17, header <charconv>) is the low-level building block: it writes the digits into a char range you give it and returns a pointer to one past the last character written plus an error code. It never allocates, never looks at the locale and never writes a terminating '\0', which makes it the fastest option in hot loops, parsers and serializers. A third argument picks any base from 2 to 36. Size the buffer with std::numeric_limits, and check ec: if the buffer is too small you get std::errc::value_too_large instead of a buffer overflow.
#include <charconv> #include <iostream> #include <limits> #include <string> #include <string_view> #include <system_error> int main() { // Big enough for any long long: its digits, a sign, one spare constexpr int size = std::numeric_limits<long long>::digits10 + 2; char buf[size]; std::cout << "buffer: " << size << " chars\n"; // Writes into the buffer: no allocation, no locale, no '\0' auto [end, ec] = std::to_chars(buf, buf + size, -1234); if (ec == std::errc()) { std::string_view text(buf, end - buf); std::cout << text << " (" << text.size() << " chars)\n"; } // Any base from 2 to 36 auto hex = std::to_chars(buf, buf + size, 255, 16); std::cout << std::string_view(buf, hex.ptr - buf) << '\n'; auto bin = std::to_chars(buf, buf + size, 10, 2); std::string bits(buf, bin.ptr); // copy into a std::string std::cout << bits << '\n'; // A buffer that is too small gives an error, never an overflow char tiny[3]; auto r = std::to_chars(tiny, tiny + 3, 123456); if (r.ec == std::errc::value_too_large) { std::cout << "123456 does not fit in 3 chars\n"; } }
Output
digits10 + 2 is buffer: 20 chars for long long, one for the sign and one because digits10 counts only the digits every value of the type can hold. The result is a range, not a C string, so the example wraps it in a std::string_view (-1234 (5 chars)) or copies it into a std::string (1010). Hex comes out in lower case, ff. The 3-char buffer can't hold 123456, so the call reports value_too_large and the program prints 123456 does not fit in 3 chars.
5Mistakes that compile but print the wrong thing
The worst int-to-string bugs aren't compile errors. A string literal is an array of char, so "Score: " + n moves a pointer n characters into it. std::string has += and = overloads for a single char, and an int converts to char silently, so s += 65 appends one letter. In the other direction, char and std::uint8_t are integer types for to_string but characters for streams. And to_string on a double uses a fixed six decimals. Each case below prints what really happens.
#include <cstdint> #include <iostream> #include <sstream> #include <string> int main() { int n = 5; // A string literal plus an int is pointer arithmetic: it skips // n characters (past the end it would be undefined behaviour) const char* p = "Score: " + n; std::cout << '[' << p << "]\n"; std::cout << "Score: " + std::to_string(n) << '\n'; // the fix // += and = with an int pick the char overload std::string s = "Total: "; s += 65; // appends the character 'A', not "65" std::cout << s << '\n'; s = 66; // the whole string becomes "B" std::cout << s << '\n'; // A char holds a number: to_string prints the code, << the character char c = '7'; std::cout << std::to_string(c) << ' ' << c << ' ' << c - '0' << '\n'; // std::uint8_t is a char type, so a stream prints it as a character std::uint8_t level = 65; std::ostringstream out; out << level << ' ' << +level; // unary + promotes it to int std::cout << out.str() << ' ' << std::to_string(level) << '\n'; // to_string on a double always prints six decimals std::cout << std::to_string(0.1) << ' ' << std::to_string(1e-7) << '\n'; }
Output
"Score: " + 5 skipped five characters and printed [: ]; a larger number would point past the end of the literal, which is undefined behaviour, so its output can't be relied on. With std::to_string the line is Score: 5. s += 65 gave Total: A and s = 66 replaced the whole string with B. Writing s + 65 as an expression is at least caught: it fails with error: no match for 'operator+', because the char overload of + is a template that won't convert the int. The char line reads 55 7 7: to_string('7') prints the character code, and c - '0' is the digit's value. The uint8_t line reads A 65 65, and unary + is the usual fix for streams. Finally, 0.1 becomes 0.100000 and 1e-7 becomes 0.000000. For floating-point values use std::format, which prints the shortest form that reads back as the same value: 0.1 and 1e-07.
6Which should you use?
Reach for std::to_string first: it's short, clear and fine for almost every program. Switch to std::format as soon as you need padding, a base or a full sentence, and to std::to_chars only when profiling shows the conversion matters.
| Method | Padding and base | Standard | Best for |
|---|---|---|---|
| std::to_string(n) | No | C++11 | Everyday conversion and + concatenation |
| std::format("{:05}", n) | Yes | C++20 | Leading zeros, hex, binary, whole messages |
| std::ostringstream << n | Yes, sticky | Any | Older code, types with operator<< |
| std::to_chars(first, last, n) | Base only | C++17 | Hot paths, fixed buffers, no allocation |
Frequently asked questions
Does C++ have itoa?
No. itoa is a non-standard extension from old C compilers and GCC does not provide it: calling it here fails with error: 'itoa' was not declared in this scope. In C++ use std::to_string(n) for a std::string, or std::to_chars(first, last, n, base) when you want digits in your own char buffer and a base other than 10, which is what itoa was usually used for.
How do I convert an int to a string with leading zeros in C++?
Use std::format("{:05}", n), which gives 00042 for 42; the 5 is the total width, and a minus sign counts toward it, so -42 gives -0042. Before C++20, write into a std::ostringstream with std::setw(5) << std::setfill('0') from <iomanip>. std::to_string has no padding option.
How do I convert an int to a hex or binary string in C++?
With std::format: {:x} gives ff for 255, {:X} gives FF, {:#x} gives 0xff, and {:b} gives binary such as 101 for 5. std::to_chars(buf, buf + size, n, 16) does the same into a buffer for any base from 2 to 36. On a stream, std::hex works, but it stays set for every number that follows.
How do I convert a single digit int to a char?
Add it to the character zero: char ch = '0' + d; turns 7 into '7', because the digit characters are consecutive in every character set C++ allows. The reverse is c - '0'. Don't use std::to_string on a char: it prints the character code, so std::to_string('7') is 55.
Should I use sprintf or snprintf to convert an int?
Only if you are working with C APIs. sprintf has no buffer size, so a long number can overflow the buffer. snprintf(buf, sizeof buf, "%05d", 42) is safe, writes 00042 with its \0, and returns the length, 5. But a wrong format specifier compiles and prints garbage, while std::format checks its pattern at compile time and returns a std::string.
Why does printing a uint8_t show a letter instead of a number?
std::uint8_t and std::int8_t are aliases for unsigned char and signed char, and streams print char types as characters, so 65 shows as A. Promote it to int before printing with unary plus (+level) or static_cast<int>(level), or convert it with std::to_string, which gives 65.