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。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章