Converting an int to std::string
You can use std::to_string in C++11
int i = 3;
std::string str = std::to_string(i);
Easiest way to convert int to string in C++
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)
How can I convert a std::string to int?
In C++11 there are some nice new convert functions from std::string
to a number type.
So instead of
atoi( str.c_str() )
you can use
std::stoi( str )
where str
is your number as std::string
.
There are version for all flavours of numbers:long stol(string)
, float stof(string)
, double stod(string)
,...
see http://en.cppreference.com/w/cpp/string/basic_string/stol
Append int to std::string
TL;DR operator+=
is a class member function in class string
, while operator+
is a template function.
The standard class template<typename CharT> basic_string<CharT>
has overloaded function basic_string& operator+=(CharT)
, and string is just basic_string<char>
.
As values that fits in a lower type can be automatically cast into that type, in expression s += 2
, the 2 is not treated as int
, but char
instead. It has exactly the same effect as s += '\x02'
. A char with ASCII code 2 (STX) is appended, not the character '2' (with ASCII value 50, or 0x32).
However, string does not have an overloaded member function like string operator+(int)
, s + 2
is not a valid expression, thus throws an error during compilation. (More below)
You can use operator+ function in string in these ways:
s = s + char(2); // or (char)2
s = s + std::string(2);
s = s + std::to_string(2); // C++11 and above only
For people concerned about why 2 isn't automatically cast to char
with operator+
,
template <typename CharT>
basic_string<CharT>
operator+(const basic_string<CharT>& lhs, CharT rhs);
The above is the prototype[note] for the plus operator in s + 2
, and because it's a template function, it is requiring an implementation of both operator+<char>
and operator+<int>
, which is conflicting. For details, see Why isn't automatic downcasting applied to template functions?
Meanwhile, the prototype of operator+=
is:
template <typename CharT>
class basic_string{
basic_string&
operator+=(CharT _c);
};
You see, no template here (it's a class member function), so the compiler deduces that type CharT is char
from class implementation, and int(2)
is automatically cast into char(2)
.
Note: Unnecessary code is stripped when copying from C++ standard include source. That includes typename 2 and 3 (Traits and Allocator) for template class "basic_string", and unnecessary underscores, in order to improve readability.
Overloading conversion operator from int to std::string
There's a function for it in the standard library. The aptly named std::to_string
:
int a = 5;
printToLog(std::to_string(a) + " bombs have been planted.");
You cannot add a conversion operator for this purpose. Such an operator can only be a member of a class type, and int
is not a class type. Neither can you add a converting constructor to std::string
. Use the mechanism the standard gives you.
Convert standard C++ int to String^
int count = 100;
System::String^ s = count.ToString();
Convert a number to a string with specified length in C++
or using the stringstreams:
#include <sstream>
#include <iomanip>
std::stringstream ss;
ss << std::setw(10) << std::setfill('0') << i;
std::string s = ss.str();
I compiled the information I found on arachnoid.com because I like the type-safe way of iostreams more. Besides, you can equally use this code on any other output stream.
Converting integer to string in c++
Character code for numbers are not equal to the integer the character represents in typical system.
It is granteed that character codes for decimal digits are consecutive (N3337 2.3 Character sets, Paragraph 3), so you can add '0'
to convert one-digit number to character.
#include <iostream>
using namespace std;
int main()
{
string s;
int b=5;
s.push_back((char)(b + '0'));
cout<<s<<endl;
}
Integer to hex string in C++
Use <iomanip>
's std::hex
. If you print, just send it to std::cout
, if not, then use std::stringstream
std::stringstream stream;
stream << std::hex << your_int;
std::string result( stream.str() );
You can prepend the first <<
with << "0x"
or whatever you like if you wish.
Other manips of interest are std::oct
(octal) and std::dec
(back to decimal).
One problem you may encounter is the fact that this produces the exact amount of digits needed to represent it. You may use setfill
and setw
this to circumvent the problem:
stream << std::setfill ('0') << std::setw(sizeof(your_type)*2)
<< std::hex << your_int;
So finally, I'd suggest such a function:
template< typename T >
std::string int_to_hex( T i )
{
std::stringstream stream;
stream << "0x"
<< std::setfill ('0') << std::setw(sizeof(T)*2)
<< std::hex << i;
return stream.str();
}
Related Topics
For Purposes of Ordering, Is Atomic Read-Modify-Write One Operation or Two
Why Does Gcc Allow Char Array Initialization with String Literal Larger Than Array
How to Determine If a C++ Object Has Been Deallocated
Is There a Name for This Tuple-Creation Idiom
Libraries in /Usr/Local/Lib Not Found
Initializing Default Values in a Struct
How to Overload Unary Minus Operator in C++
Static Analysis Tool to Detect Abi Breaks in C++
How to Avoid Static Member Function When Using Gsl with C++
Can't C++ Pod Type Have Any Constructor
How to Emulate _Mm256_Loadu_Epi32 with Gcc or Clang
What Exactly Is Streambuf? How to Use It
Heap Corruption Under Win32; How to Locate
Thread Safe Lazy Construction of a Singleton in C++