Convert int to string in C++

A modern guide to type conversion methods and performance

Overview

Converting an integer to a string is one of the most common tasks in C++ programming. Unlike some higher-level languages, C++ offers multiple ways to achieve this, each with its own pros and cons regarding syntax, safety, and performance.

Method 1: std::to_string (Recommended)

Standard: C++11 and later

This is the most modern, straightforward, and readable way to convert numbers to strings. It works for int, long, float, double, etc.

#include <iostream> #include <string> int main() { int num = 42; std::string str = std::to_string(num); std::cout << "The string is: " << str << std::endl; return 0; }

Method 2: std::stringstream

Before C++11, streams were the standard way to perform conversions. This method is flexible but slower due to the overhead of stream initialization.

#include <iostream> #include <string> #include <sstream> int main() { int num = 12345; std::stringstream ss; ss << num; std::string str = ss.str(); std::cout << "Converted: " << str << std::endl; return 0; }

Method 3: std::format (C++20)

For modern projects using C++20, std::format provides a Python-like formatting syntax that is highly efficient.

#include <format> #include <string> int main() { int num = 99; std::string str = std::format("{}", num); return 0; }

Comparison Table

Method C++ Version Performance Readability
std::to_string C++11 Fast Excellent
std::format C++20 Very Fast Excellent
std::stringstream C++98 Slow Good
sprintf (C-style) Any Fast Poor (Unsafe)

Frequently Asked Questions

Is `itoa` a standard function?

No, itoa is a non-standard C extension. It works on some compilers but is not portable. Use std::to_string instead.

Which method is the fastest?

std::to_char (C++17) is theoretically the fastest for low-level performance, but std::to_string is sufficient for 99% of use cases.

Related Topics