How to convert int to string in C++?

To convert an integer to a string in C++, you can use one of the following methods:

1. std::to_string() (C++11 and later)

The simplest and most modern approach:

#include <string>

int num = 42;
std::string str = std::to_string(num); // "42"
  • Works for: int, long, long long, unsigned, float, double, etc.
  • Limitations: Requires C++11 or newer.

2. std::stringstream (All C++ versions)

Use a string stream for compatibility with older C++ standards:

#include <sstream>
#include <string>

int num = 42;
std::stringstream ss;
ss << num; // Insert integer into the stream
std::string str = ss.str(); // Extract as string ("42")

3. sprintf or snprintf (C-style)

A C-style method using formatted strings:

#include <cstdio>
#include <string>

int num = 42;
char buffer[12]; // Enough for 32-bit integers (including sign and null terminator)
snprintf(buffer, sizeof(buffer), "%d", num); // Safe buffer size
std::string str(buffer); // Convert to std::string ("42")
  • Advantage: Works in all C++ versions.
  • Caution: Use snprintf (not sprintf) to avoid buffer overflows.

4. Boost lexical_cast (Third-Party)

If you use the Boost library:

#include <boost/lexical_cast.hpp>
#include <string>

int num = 42;
std::string str = boost::lexical_cast<std::string>(num); // "42"
  • Install Boost: Required for this method.

Performance Notes

  • Fastest: std::to_string or snprintf.
  • Most Flexible: std::stringstream (handles formatting like hex, octal, etc.).

Example with Formatting

Use std::stringstream for custom formatting (e.g., hexadecimal):

#include <sstream>
#include <string>

int num = 255;
std::stringstream ss;
ss << std::hex << num; // Convert to hex
std::string str = ss.str(); // "ff"

Summary

  • For Modern C++: Use std::to_string().
  • For Compatibility: Use std::stringstream or snprintf.
  • Avoid: Legacy C functions like itoa (non-standard and unsafe).

Let me know if you need further details!

Leave a Reply

Your email address will not be published. Required fields are marked *