像是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;
}