How do you convert an int to a string in C++?

I’m trying to figure out the best way to convert an int to a string in C++. I’m aware of using itoa() and stringstream, but I’d like to know if there are any other modern or standard methods that are more efficient or readable. What’s commonly used in real-world C++ code today?

I’ve been working with C++ for quite a while now, and in modern C++ (C++11 and above), the cleanest and most efficient way to convert an int to a string is definitely using std::to_string(). It’s simple, safe, and part of the standard library, so you don’t have to worry about compatibility issues. You just write:

int num = 42;
std::string str = std::to_string(num);

In my experience, it’s a no-brainer for most cases. Way better than messing around with things like stringstream, unless you’re dealing with more complex formatting scenarios.

Totally agree, Joe! I used to use stringstream all the time before C++11 for c++ int to string conversions, especially if I was working with multiple types or needed custom formatting. It still has its place, and it works great for things like formatting numbers with precision or adding cus

std::stringstream ss;
ss << 100;
std::string result = ss.str();

But honestly, these days, for just quickly converting an int to a string, std::to_string is my go-to. It’s just cleaner and more readable in most everyday scenarios.

I’ve definitely been burned by using itoa() in the past, so I avoid it now. It’s not part of the C++ standard and can be tricky with portability across different compilers. If you want something simple, std::to_string() is the way to go. I’ve found it to be reliable and consistent in all my projects since C++11. That being said, if you’re working on something that requires base conversions or a really specific format, you might need to look beyond std::to_string() or stringstream. But for general use, std::to_string is just a safer bet for converting a c++ int to string.