天天看點

string和int之間的轉換

(1)int轉換為字元串

用字元串流實作int to str

string int2str(int num)   // int to str
{
	stringstream ss;
	ss<<num;
	string str;
	ss>>str;
	return str;
}
           

itoa函數:char* itoa (int value, char* str, int base);  //base為進制度,如10,2,16等

sprintf也可以把整數列印到字元串中,是以sprintf 在大多數場合可以替代itoa。

int sprintf ( char * str, const char * format, ... );

例如:

sprintf(s,"%d %d"123, 4567); //産生:" 123 4567",中間%d %d為列印的格式,可以各種設定。

傳回值:

On success,the total number of characters written isreturned.

On failure, a negative number is returned.

------------------------------------------------------------------------------------------

(2)字元串轉換為int

intstr2int(string str)   //str toint
{
	int num;
	num=atoi(const_cast(str.c_str()));     //intatoi ( const char * str );
	return num;
}