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。
2、使用sprintf
// int sprintf( char *buffer, const char *format, [ argument] … );
//參數列表
// buffer:char型指針,指向將要寫入的字符串的緩衝區。
// format:格式化字符串。
// [argument]...:可選參數,可以是任何類型的數據。
// 返回值:字符串長度(strlen)
int aa = 30;
char c[8];
int length = sprintf(c, "%05X", aa);
cout<<c<<endl; // 0001E
3、使用stringstream
int aa = 30;
stringstream ss;
ss<<aa;
string s1 = ss.str();
cout<<s1<<endl; // 30
string s2;
ss>>s2;
cout<<s2<<endl; // 30
可以這樣理解,stringstream可以吞下不同的類型,根據s2的類型,然後吐出不同的類型。
4、使用boost庫中的lexical_cast
int aa = 30;
string s = boost::lexical_cast<string>(aa);
cout<<s<<endl; // 30
3和4只能轉化爲10進制的字符串,不能轉化爲其它進制的字符串。
string轉化爲int
1、使用strtol(string to long)
string s = "17";
char* end;
int i = static_cast<int>(strtol(s.c_str(),&end,16));
cout<<i<<endl; // 23
i = static_cast<int>(strtol(s.c_str(),&end,10));
cout<<i<<endl; // 17
2、使用sscanf
int i;
sscanf("17","%D",&i);
cout<<i<<endl; // 17
sscanf("17","%X",&i);
cout<<i<<endl; // 23
sscanf("0X17","%X",&i);
cout<<i<<endl; // 23
3、使用stringstream
string s = "17";
stringstream ss;
ss<<s;
int i;
ss>>i;
cout<<i<<endl; // 17
注:stringstream可以吞下任何類型,根據實際需要吐出不同的類型。
4、使用boost庫中的lexical_cast
string s = "17";
int i = boost::lexical_cast<int>(s);
cout<<i<<endl; // 17
本文轉載自:Andy Niu