Easiest way to convert int to string in C++
What is the easiest way to convert from int to equivalent string in C++. I am aware of two methods. Is there any easier 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++0x 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
.
std::string s = std::to_string(42);
is therefore the shortest way I can think of.
Note: see [string.conversions] (21.5 in n3242)
http://stackoverflow.com/questions/5590381/easiest-way-to-convert-int-to-string-in-cint本身也要用一串字符表示,前后没有双引号,告诉编译器把它当作一个数解释。缺省情况下,是当成10进制(dec)来解释,如果想用8进制,16进制,怎么办?加上前缀,告诉编译器按照不同进制去解释。8进制(oct)---前缀加0,16进制(hex)---前缀加0x或者0X。
string前后加上双引号,告诉编译器把它当成一串字符来解释。
注意:对于字符,需要区分字符和字符表示的数值。比如:char a = 8;char b = '8',a表示第8个字符,b表示字符8,是第56个字符。
int转化为string
1、使用itoa(int to string)
//char *itoa( int value, char *string,int radix);
// 原型说明:
// value:欲转换的数据。
// string:目标字符串的地址。
// radix:转换后的进制数,可以是10进制、16进制等。
// 返回指向string这个字符串的指针
int aa = 30;
char c[8];
itoa(aa,c,16);
cout<<c<<endl; // 1e
注意:itoa并不是一个标准的C函数,它是Windows特有的,如果要写跨平台的程序,请用sprintf。