这是leetcode 中遇到的一个纠结了很久的问题,试过几种,总结如下:
int a=247;
char c[10];
string b
方法一:使用sprintf_s(或sprintf)
sprintf_s(c,"%d",a);
string b(c);
在VS中使用sprintf会有一个warning,并且建议采用sprintf_s。
用哪个还是看情况吧,(leetcode中用sprintf_s行不通)。
方法二:_itoa_s
itoa(a,c,10);
string b(c);
编译有warning: warning C4996: ‘itoa’: The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _itoa. See online help for details.
按照提示将itoa替换为_itoa如下:
_itoa(a,c,10);
依然会产生一个warning:warning C4996: ‘_itoa’: This function or variable may be unsafe. Consider using _itoa_s instead.
按照提示继续用-_itoa_s: _itoa_s(a,c,10);
编译正常无bug。
Note:使用新的_itoa_s。
方法三:stringstream
#include<sstream>
stringstream ss;
ss<<a;
b=ss.str();
如果循环中使用stringstream的话,要对stringstream进行清空
注意:ss.clear()只是重置了stringstream的状态标志,并没有清空数据。如果需要清空数据,则需要ss.str(“”);
如下:
for()
{
ss.str("");
ss<<a;
}
方法四:strstream
#include<strstream>
或者#inclde<stringstream>
strstream ss
ss<<a;
ss>>b
如果进行循环的话,与stringstream不同,strstream使用clear()是进行清空,.str(“”)标志位没有发生改变,无法写入。
还有别的方法,但coding过的就这几种。