Logo

How to convert int to string in C++?

Converting an integer to a string is a fundamental operation in C++. Whether you’re formatting output for logging, building complex strings, or simply doing text-based manipulations, it’s helpful to know multiple approaches. Below are various ways to transform an int into a std::string, along with best practices and performance considerations.

1. Using std::to_string (C++11 and Above)

Starting from C++11, the most straightforward way to convert an integer to a string is with std::to_string.

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

Why Use It:

  • Simplicity: Single function call.
  • Readability: Clear intent—anyone reading the code knows what is happening immediately.

2. Using std::stringstream

std::stringstream is a versatile class that combines reading and writing operations on strings.

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

Why Use It:

  • Flexibility: You can format strings by chaining together multiple insertions (<<).
  • Legacy Compatibility: Before C++11, std::stringstream was a common choice.

3. Using std::format (C++20)

If your compiler supports C++20, std::format (in <format>) offers a Python-like formatting experience.

#include <format> #include <iostream> #include <string> int main() { int num = 42; // Using std::format std::string str = std::format("{}", num); std::cout << "Number: " << str << std::endl; return 0; }

Why Use It:

  • Enhanced Formatting: Offers advanced options similar to Python’s format() or f-strings.
  • Future-Proof: Modern and likely to gain traction as more compilers implement C++20 features.

4. Using C-Style sprintf or snprintf

If you come from a C background or need to integrate with older code, you might see sprintf or snprintf used. However, this approach can be riskier (buffer overflows if not used carefully) compared to safer C++ alternatives.

#include <cstdio> #include <string> #include <iostream> int main() { int num = 42; char buffer[50]; // Ensure the buffer is large enough std::sprintf(buffer, "%d", num); std::string str(buffer); std::cout << "Number: " << str << std::endl; return 0; }

Why Use It:

  • Legacy or Embedded Environments: Sometimes you have no choice if you’re working in older systems.
  • Control: You can precisely control formatting with the %d, %f, etc. placeholders.

5. Using Boost’s lexical_cast

If your project already uses Boost, you might leverage lexical_cast.

#include <boost/lexical_cast.hpp> #include <string> #include <iostream> int main() { int num = 42; std::string str = boost::lexical_cast<std::string>(num); std::cout << "Number: " << str << std::endl; return 0; }

Why Use It:

  • Powerful: Can convert between many types.
  • Readable: Clearly states conversion from an integer to a string.

Best Practices

  1. Use std::to_string for Simplicity: If you’re coding in C++11 or later, this is the go-to method for most use cases.
  2. Be Mindful of Performance: If you’re converting tens of thousands of integers per second, measure to see which approach works best in your environment.
  3. Consider Formatting Requirements: If you need advanced formatting (fixed width, padding, etc.), std::format or std::stringstream may be more suitable.
  4. Code Clarity Over Micro-Optimization: It’s usually better to have clear, maintainable code than to micro-optimize integer-to-string conversions unless performance is truly critical.

Why This Matters for Coding Interviews

String manipulation is a fundamental coding skill. Interviewers often look for a candidate’s proficiency in standard library functions and awareness of best practices. Knowing these approaches showcases both your familiarity with modern C++ features and your ability to handle backward compatibility issues.

If you’re preparing for a technical interview—especially at top-tier companies—take a structured approach to your preparation. Check out these courses from DesignGurus.io:

  1. Grokking the Coding Interview: Patterns for Coding Questions
    Master the recurring coding patterns tested repeatedly in interviews.
  2. Grokking Data Structures & Algorithms for Coding Interviews
    Deep-dive into crucial algorithms and data structures that underpin most coding challenges.

Additional Resources

By exploring these integer-to-string conversion techniques, you’ll not only write more flexible and powerful C++ code but also boost your interview readiness with a practical skill that’s often tested in coding challenges. Happy coding!

CONTRIBUTOR
TechGrind