How To Convert Int To String C++

4 min read

How to Convert int to string in C++

Converting an integer to a string is a common task in C++ programming, whether you need to display numeric values in a user interface, log data, or build formatted output. The language provides several ways to perform this conversion, each with its own advantages in terms of readability, performance, and flexibility. This guide explores the most reliable techniques, explains when to use each one, and highlights common pitfalls to avoid.

Why Converting int to string Matters

In many applications, numeric data must be presented as text. Here's one way to look at it: printing a score in a game, generating a CSV line, or concatenating numbers with other strings all require an integer‑to‑string transformation. Using the correct method ensures that the conversion is safe, efficient, and maintains the exact value without unintended side effects such as buffer overflows or loss of precision.

Method 1: Using std::to_string

The simplest and most modern approach is the std::to_string function introduced in C++11. It overloads for all fundamental integer types and returns a std::string containing the decimal representation.

#include 
#include 

int main() {
    int number = 42;
    std::string text = std::to_string(number);
    std::cout << "The number is: " << text << std::endl;
    return 0;
}

Advantages

  • Concise: One line of code does the conversion.
  • Type‑safe: No format strings to mismatched specifiers.
  • Locale‑independent: Always uses the classic “C” locale, producing predictable output.

Limitations

  • Only supports decimal base; hexadecimal, octal, or custom bases require additional steps.
  • Performance is adequate for most cases but may be slightly slower than a hand‑crafted sprintf in tight loops.

Method 2: Using std::stringstream

When you need more control over formatting—such as setting width, fill characters, or number bases—std::stringstream offers a flexible solution.

#include 
#include 
#include    // for std::hex, std::setw, etc.
#include 

int main() {
    int value = 255;
    std::stringstream ss;
    ss << std::hex << std::setw(2) << std::setfill('0') << value; // hexadecimal, two‑digit
    std::string result = ss.str();
    std::cout << "Hex value: " << result << std::endl; // outputs "ff"
    return 0;
}

Real talk — this step gets skipped all the time.

Advantages

  • Full formatting capabilities via manipulators (std::hex, std::dec, std::oct, std::setw, std::setfill).
  • Easy to concatenate multiple values in a single stream.

Limitations

  • Slightly more verbose than std::to_string.
  • Involves dynamic memory allocation for the internal buffer, which may affect performance in high‑frequency scenarios.

Method 3: Using sprintf / snprintf

The C‑style functions sprintf and its safer counterpart snprintf allow direct conversion into a character array. While they are fast, they require careful buffer management.

#include 
#include 
#include 

int main() {
    int num = -12345;
    char buffer[32]; // sufficiently large for any 32‑bit int plus sign and terminator
    std::snprintf(buffer, sizeof(buffer), "%d", num);
    std::string text(buffer);
    std::cout << "Formatted: " << text << std::endl;
    return 0;
}

Advantages

  • Very fast, especially when the buffer size is known and reused.
  • Supports all printf‑style format specifiers (hex, octal, padding, etc.).

Limitations

  • Risk of buffer overflow if the buffer is too small; snprintf mitigates this but still requires correct size calculation.
  • Returns a C‑string; you must copy or construct a std::string afterward.
  • Less type‑safe than C++ alternatives; mismatched specifiers lead to undefined behavior.

Method 4: Using Boost lexical_cast

If you already depend on the Boost libraries, boost::lexical_cast provides a uniform way to convert between types, including int to string.

#include 
#include 
#include 

int main() {
    int x = 999;
    std::string s = boost::lexical_cast(x);
    std::cout << "Boost cast: " << s << std::endl;
    return 0;
}

Advantages

  • Consistent syntax for many type conversions.
  • Throws boost::bad_lexical_cast on failure, enabling exception‑based error handling.

Limitations

  • Introduces an external dependency (Boost) if not already used.
  • Slight overhead due to exception machinery and internal stream usage.

Method 5: Using fmt library (C++20‑style formatting)

The {fmt} library (and the upcoming std::format in C++20) offers a modern, type‑safe formatting interface that is both fast and readable Simple, but easy to overlook..

#include 
#include 
#include 

int main() {
    int temperature = -40;
    std::string out = fmt::format("{}", temperature);
    std::cout << fmt::println("Temperature: {}", out);
    return 0;
}

Advantages

  • Syntax similar to Python’s str.format or f‑strings.
  • Compile‑time checking of format strings (when using std::format).
  • High performance, often comparable to sprintf.

Limitations

  • Requires linking against the fmt library (header‑only version available).
  • Not part of the standard library until C++20; older compilers need the external library.

Performance Comparison

Method Typical Speed (relative) Safety Flexibility
std::to_string 1.In real terms, 0x (baseline) High Low (decimal only)
std::stringstream 0. 6x–0.Plus, 8x High High (manipulators)
snprintf 1. 2x–1.
New and Fresh

Just Released

Close to Home

You're Not Done Yet

Thank you for reading about How To Convert Int To String C++. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home