Easiest way to convert int to string in C++

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-c


上文漏洞颇多,更好的参见帖子http://www.cnblogs.com/nzbbody/p/3504199.html

int本身也要用一串字符表示,前后没有双引号,告诉编译器把它当作一个数解释。缺省情况下,是当成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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值