How can I convert from int to the equivalent string in C++? I am aware of two methods. Is there another way?
(1)
int a = 10; char *intStr = itoa(a); string str = string(intStr); (2)
int a = 10; stringstream ss; ss << a; string str = ss.str(); C++11 introduces std::stoi (and variants for each numeric type) and std::to_string, the counterparts of the C atoi and itoa but expressed in term of std::string.
#include <string> std::string s = std::to_string(42); is therefore the shortest way I can think of. You can even omit naming the type, using the auto keyword:
auto s = std::to_string(42); Note: see [string.conversions] (21.5 in n3242)
Note: for faster/non-allocating conversions, consider the {fmt} library's fmt::format_int as per @vitaut's answer.
g++ -std=c++11 someFile.ccstd in every compiler I know of except for one.string s = to_string((_ULonglong)i);C++20: std::format would be the idiomatic way now.
C++17:
Picking up a discussion with @v.oddou a couple of years later, C++17 has delivered a way to do the originally macro-based type-agnostic solution (preserved below) without going through macro ugliness.
// variadic template template < typename... Args > std::string sstr( Args &&... args ) { std::ostringstream sstr; // fold expression ( sstr << std::dec << ... << args ); return sstr.str(); } Usage:
int i = 42; std::string s = sstr( "i is: ", i ); puts( sstr( i ).c_str() ); Foo x( 42 ); throw std::runtime_error( sstr( "Foo is '", x, "', i is ", i ) ); C++98:
Since "converting ... to string" is a recurring problem, I always define the SSTR() macro in a central header of my C++ sources:
#include <sstream> #define SSTR( x ) static_cast< std::ostringstream & >( \ ( std::ostringstream() << std::dec << x ) ).str() Usage is as easy as could be:
int i = 42; std::string s = SSTR( "i is: " << i ); puts( SSTR( i ).c_str() ); Foo x( 42 ); throw std::runtime_error( SSTR( "Foo is '" << x << "', i is " << i ) ); The above is C++98 compatible (if you cannot use C++11 std::to_string), and does not need any third-party includes (if you cannot use Boost lexical_cast<>); both these other solutions have a better performance though.
dynamic_cast but I am using clang to compile so it complains about it. If I just omit the dynamic_cast then it compiles fine; what purpose does the dynamic_cast serve in this case? We are already creating an ostringstream, so why cast it?ostringstream, we called operator<<() on it, which returns ostream & -- for which .str() is not defined. I really wonder how clang would make this work without the cast (or why it generates an error with it). This construct is published in many places, and I've used it for over a decade on many different compilers, including MSVC, GCC, and XLC, so I am rather surprised clang balks at it.do { } while( 0 ) would not add anything. With 2. and 3. you probably got a point -- this could be done with a static cast, and perhaps one of you template wizards out there could come up with a "nicer" interface. But as I said, this is by no means an invention of myself. Look around, this macro (macro!) is quite ubiquitous. That's a case of POLA in itself. I might toy with this a bit to make it more "streamlined".Starting with C++11, there's a std::to_string function overloaded for integer types, so you can use code like:
int a = 20; std::string s = std::to_string(a); // or: auto s = std::to_string(a); The standard defines these as being equivalent to doing the conversion with sprintf (using the conversion specifier that matches the supplied type of object, such as %d for int), into a buffer of sufficient size, then creating an std::string of the contents of that buffer.
For older (pre-C++11) compilers, probably the most common easy way wraps essentially your second choice into a template that's usually named lexical_cast, such as the one in Boost, so your code looks like this:
int a = 10; string s = lexical_cast<string>(a); One nicety of this is that it supports other casts as well (e.g., in the opposite direction works just as well).
Also note that although Boost lexical_cast started out as just writing to a stringstream, then extracting back out of the stream, it now has a couple of additions. First of all, specializations for quite a few types have been added, so for many common types, it's substantially faster than using a stringstream. Second, it now checks the result, so (for example) if you convert from a string to an int, it can throw an exception if the string contains something that couldn't be converted to an int (e.g., 1234 would succeed, but 123abc would throw).
I usually use the following method:
#include <sstream> template <typename T> std::string NumberToString ( T Number ) { std::ostringstream ss; ss << Number; return ss.str(); } It is described in details here.
clear() a newly created ostringstream object. clear() resets the error/eof flags, and there has not been any error/eof condition generated yet.NumberToString(23213.123) produces 23213.1 while std::to_string(23213.123) produces 23213.123000 What happens there?.flags(...) to read & clear formatting flags, and .str("") to clear an existing string.You can use std::to_string available in C++11 as suggested by Matthieu M.:
std::string s = std::to_string(42); Or, if performance is critical (for example, if you do lots of conversions), you can use fmt::format_int from the {fmt} library to convert an integer to std::string:
std::string s = fmt::format_int(42).str(); Or a C string:
fmt::format_int f(42); const char* s = f.c_str(); The latter doesn't do any dynamic memory allocations and is more than 70% faster than libstdc++ implementation of std::to_string on Boost Karma benchmarks. See Converting a hundred million integers to strings per second for more details.
Disclaimer: I'm the author of the {fmt} library.
c_str() returns a pointer to a buffer declared inside the fmt::FormatInt class -- so the pointer returned will be invalid at the semicolon -- see also stackoverflow.com/questions/4214153/lifetime-of-temporariesstd::string::c_str() (thus the naming). If you want to use it outside of the full expression construct an object FormatInt f(42); Then you can use f.c_str() without a danger of it being destroyed.fmt::format_int looks great indeed.If you have Boost installed (which you should):
#include <boost/lexical_cast.hpp> int num = 4; std::string str = boost::lexical_cast<std::string>(num); It would be easier using stringstreams:
#include <sstream> int x = 42; // The integer string str; // The string ostringstream temp; // 'temp' as in temporary temp << x; str = temp.str(); // str is 'temp' as string Or make a function:
#include <sstream> string IntToString(int a) { ostringstream temp; temp << a; return temp.str(); } C++ has evolved over time, and with it the methods to convert an int to a string. I will provide a summary in this answer. Note that some methods don't give you a std::string directly, but a char*. You can easily convert char* to the former, and in some cases it's beneficial to avoid std::string.
The following table compares all options (only C++ standard options, no third-party libraries) from most recent to least recent.
| Method | Result | Pros & Cons |
|---|---|---|
| std::format c++20 | std::string | ✔️ universal method (for formattable types) ✔️ supports common bases, and locale ❌ slow to compile ❌ slow (forward to std::vformat) |
| std::to_chars c++17 | written tochar[] | ✔️ fast and zero overhead (no dynamic allocations) ✔️supports ANY base as run-time argument ❌ only works for fundamental types ❌ interface is not ergonomic |
| std::to_string c++11 | std::string | ✔️ concise and self-explanatory ✔️ zero overhead (if you need a std::string)❌ only works for fundamental types ❌ base 10 only |
| std::ostringstream c++98 | std::string | ✔️ universal method (for types with << operator)✔️ considers locale (e.g. can change base) ❌ slow, and high overhead of streams |
| std::sprintf c++98 | written tochar[] | ✔️ smallest assembly output ✔️ supports some bases ✔️ compatible with C, unlike all other methods ❌ only works for fundamental types ❌ interface is not ergonomic ❌ no type safety |
Use std::to_string if you just need to turn an int into a decimal string. It's simple, elegant, and correct.
If you can't use std::to_string, choose another option based on the features you need. Prefer more modern solutions like std::to_chars over older solutions like std::sprintf.
std::formatstd::string d = std::format("{}", 100); // d = "100" std::string h = std::format("{:#x}", 15); // h = "0xf" std::to_charsstd::array<char, 5> a; auto [ptr, ec] = std::to_chars(a.data(), a.data() + a.size(), 1234); // a = {'1', '2', '3', '4', indeterminate} (no null terminator!) // ptr points to 4, and ec == std::errc{} // notice that there is no null terminator std::string_view view(a.data(), ptr); // string_view doesn't require null terminators std::string s(a.data(), ptr); // wrapping in a std:string kinda defeats the point std::to_stringstd::string d = std::to_string(100); // d = "100" std::ostringstreamstd::string d = (std::ostringstream() << 100).str(); // d = "100" std::string h = (std::ostringstream() << std::hex << 15).str(); // h = "0xf" Note: these one-liners rely on LWG 1203 (C++20), but recent compilers allow it in C++11 mode too. Update your compiler, or create a separate std::ostringstream stream variable if it doesn't work.
sprintf / snprintfchar a[20]; sprintf(a, "%d", 15); // a = {'1', '5', '\0', ?, ?, ?, ...} snprintf(a, sizeof(a), "%#x", 15); // a = {'0', 'x', 'f', '\0', ?, ?, ...} std::string s = a; std::ostringstream does not work for me. g++ 4.8.5 issues an error: class std::basic_ostream<char> has no member named str. Is there any way to fix that?std::ostringstream example actually relies on LWG 1203 which was applied to C++20. However, recent compilers allow it even in C++11 mode (godbolt.org/z/Pdr1zaTnf). GCC 4 is really old, so either you could upgrade your compiler, or you could make it work by not using the one-liner but creating a separate std::ostringstream variable.constexpr? Is there any function for that planned in C++26?sprintf() is pretty good for format conversion. You can then assign the resulting C string to the C++ string as you did in 1.
snprintf it has no idea how large said buffer is, and may overwrite past the end.NULL and zero size to get the necessary buffer size.snprintf (note the SNP prefix) and sprintf (note the SP prefix). You pass the size to the former, and it takes care not to overflow, however the latter knows not the size of the buffer and thus may overflow.snprintf variant first and a sprintf variant after that. As the buffer size is known by then, calling sprintf becomes entirely safe.Using stringstream for number conversion is dangerous!
See std::ostream::operator<< where it tells that operator<< inserts formatted output.
Depending on your current locale an integer greater than three digits, could convert to a string of four digits, adding an extra thousands separator.
E.g., int = 1000 could be converted to a string 1.001. This could make comparison operations not work at all.
So I would strongly recommend using the std::to_string way. It is easier and does what you expect.
From std::to_string:
C++17 provides
std::to_charsas a higher-performance locale-independent alternative.
std::to_string uses the current locale (see en.cppreference.com/w/cpp/string/basic_string/to_string , the 'Notes' section). Almost all standard tools (from stringstreams to sprintf, but also sscanf etc) are using the current locale. I wasn't aware of this until recently when it hit me hard. Currently using home-grown stuff, not hard to make.First include:
#include <string> #include <sstream> Second add the method:
template <typename T> string NumberToString(T pNumber) { ostringstream oOStrStream; oOStrStream << pNumber; return oOStrStream.str(); } Use the method like this:
NumberToString(69); or
int x = 69; string vStr = NumberToString(x) + " Hello word!." C++17 provides std::to_chars as a higher-performance locale-independent alternative.
If you need fast conversion of an integer with a fixed number of digits to char* left-padded with '0', this is the example for little-endian architectures (all x86, x86_64 and others):
If you are converting a two-digit number:
int32_t s = 0x3030 | (n/10) | (n%10) << 8; If you are converting a three-digit number:
int32_t s = 0x303030 | (n/100) | (n/10%10) << 8 | (n%10) << 16; If you are converting a four-digit number:
int64_t s = 0x30303030 | (n/1000) | (n/100%10)<<8 | (n/10%10)<<16 | (n%10)<<24; And so on up to seven-digit numbers. In this example n is a given integer. After conversion it's string representation can be accessed as (char*)&s:
std::cout << (char*)&s << std::endl; Note: If you need it on big-endian byte order, though I did not tested it, but here is an example: for three-digit number it is int32_t s = 0x00303030 | (n/100)<< 24 | (n/10%10)<<16 | (n%10)<<8; for four-digit numbers (64 bit arch): int64_t s = 0x0000000030303030 | (n/1000)<<56 | (n/100%10)<<48 | (n/10%10)<<40 | (n%10)<<32; I think it should work.
'0' is 0x30, as in ASCII. Of course, this is not an assumption you need to make at all. You can just memcpy "000" to a std::uint_fast32_t. That will copy the correct bitpattern.It's rather easy to add some syntactical sugar that allows one to compose strings on the fly in a stream-like way
#include <string> #include <sstream> struct strmake { std::stringstream s; template <typename T> strmake& operator << (const T& x) { s << x; return *this; } operator std::string() {return s.str();} }; Now you may append whatever you want (provided that an operator << (std::ostream& ..) is defined for it) to strmake() and use it in place of an std::string.
Example:
#include <iostream> int main() { std::string x = strmake() << "Current time is " << 5+5 << ":" << 5*5 << " GST"; std::cout << x << std::endl; } C++11 introduced std::to_string() for numeric types:
int n = 123; // Input, signed/unsigned short/int/long/long long/float/double std::string str = std::to_string(n); // Output, std::string If you're using the Microsoft Foundation Class library, you can use CString:
int a = 10; CString strA; strA.Format("%d", a); Use:
#define convertToString(x) #x int main() { convertToString(42); // Returns const char* equivalent of 42 } string number_to_string(int x) { if (!x) return "0"; string s, s2; while(x) { s.push_back(x%10 + '0'); x /= 10; } reverse(s.begin(), s.end()); return s; } All you have to do is use String when defining your variable (String intStr). Whenever you need that variable, call whateverFunction(intStr.toInt())
namespace std { inline string to_string(int _Val) { // Convert long long to string char _Buf[2 * _MAX_INT_DIG]; snprintf(_Buf, "%d", _Val); return (string(_Buf)); } } You can now use to_string(5).
std namespace is not something you should ever do, either. Also, it doesn't seem like _MAX_INT_DIG is a standard macro, so if it is defined wrongly, this code has the great potential of inducing undefined behaviour. -1
itoa()takes three parameters.