C++中int型与string型互相转换
像是C#,java等高级语言中,int转String类型都是很简单的,但是C++中比较麻烦:
int 转换string
string int2str( int num)
{
if (num == 0 )
return " 0 " ;
string str = "" ;
int num_ = num > 0 ? num : - 1 * num;
while (num_)
{
str = ( char )(num_ % 10 + 48 ) + str;
num_ /= 10 ;
}
if (num < 0 )
str = " - " + str;
return str;
}
string 转换int
int str2int( string str)
{
int i,len = str.size(),num = 0 ;
i = 0 ;
if (str[ 0 ] == ' - ' )
i = 1 ;
while (i < len)
{
num = num * 10 + ( int )(str[i] - ' 0 ' );
i ++ ;
}
if (str[ 0 ] == ' - ' )
num *= - 1 ;
return num;
}
补充:软件开发 , C++ ,