|

Converting Int to String in C++

Converting Int to String in C++

Converting integers to strings is a frequent operation in C++ programs. Modern C++ provides several approaches, each with different trade-offs in simplicity, performance, and flexibility.

Using std::to_string() (Recommended)

The standard library function std::to_string() (C++11 and later) is the most straightforward approach for most use cases:

#include <iostream>
#include <string>

int main() {
  int n = 123;
  std::string str = std::to_string(n);
  std::cout << n << " ==> " << str << std::endl;

  return 0;
}

This function converts signed and unsigned integers to their string representation. It handles the conversion internally and returns a std::string directly, eliminating buffer management concerns.

One caveat: std::to_string() can throw std::bad_alloc if memory allocation fails during string creation. For most applications this is not a concern, but if you’re working in extremely memory-constrained environments or need guaranteed exception handling, catch the exception explicitly:

try {
  std::string result = std::to_string(value);
} catch (const std::bad_alloc& e) {
  std::cerr << "Memory allocation failed: " << e.what() << std::endl;
}

Using std::stringstream

std::stringstream offers more flexibility when you need to combine multiple conversions or apply formatting:

#include <sstream>
#include <iostream>

int main() {
  int i = 123;
  std::stringstream ss;
  ss << i;
  std::string out_string = ss.str();
  std::cout << out_string << "\n";

  return 0;
}

This approach is useful when building complex strings with multiple values:

std::stringstream ss;
ss << "Value: " << 42 << ", Result: " << 3.14;
std::string result = ss.str();

You can also apply formatting flags for hex, octal, or other bases:

std::stringstream ss;
ss << std::hex << 255;  // Outputs "ff"
std::string hex_string = ss.str();

Using snprintf() (C-style)

While std::to_string() is preferred in modern C++, snprintf() remains useful when you need precise control over formatting or are maintaining legacy code:

#include <cstdio>
#include <iostream>

int main() {
  int number = 123;
  char out_string[128];
  int rt = snprintf(out_string, sizeof(out_string), "%d", number);

  if (rt < 0 || rt >= 128) {
    std::cerr << "snprintf() failed or buffer overflow risk" << std::endl;
  } else {
    std::cout << "out_string = \"" << out_string << "\"" << std::endl;
  }

  return 0;
}

The snprintf() function safely limits output to the buffer size and returns the number of characters written (or -1 on error). Always check the return value and ensure your buffer is large enough. For large numbers, allocate sufficient buffer space; a 128-byte buffer accommodates most integer conversions, but use std::numeric_limits<int>::digits10 + 2 for a portable upper bound.

Performance Considerations

For simple conversions, std::to_string() and snprintf() have comparable performance. std::stringstream carries slightly more overhead due to stream state management, but the difference is negligible unless converting millions of values in tight loops. Profile your specific use case if performance is critical.

Which Method to Use

  • std::to_string(): Use this for C++11 and later projects. It’s concise, safe, and idiomatic.
  • std::stringstream: Choose this when building complex strings or needing format control beyond basic decimal representation.
  • snprintf(): Reserve this for legacy code, embedded systems, or situations requiring guaranteed buffer control without exceptions.

Similar Posts

Leave a Reply

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