1. 程式人生 > >C++字串和int的相互轉換

C++字串和int的相互轉換

int本身也要用一串字元表示,前後沒有雙引號,告訴編譯器把它當作一個數解釋。預設情況下,是當成10進位制(dec)來解釋,如果想用8進位制,16進位制,怎麼辦?加上字首,告訴編譯器按照不同進位制去解釋。8進位制(oct)---字首加0,16進位制(hex)---字首加0x或者0X。string前後加上雙引號,告訴編譯器把它當成一串字元來解釋。

int轉化為string

1、使用itoa(int value, char *string, int radix)

將int整型數轉化為一個字串,並將值儲存在陣列string.其中value為要轉化的整數, radix是基數的意思,即先將value轉化為radix進位制的數,之後再儲存在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

<pre name="code" class="cpp">// 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); //X表示讀入或輸出十六進位制串
 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)

long int strtol(const char *nptr, char **endptr, int base)strtol()會將nptr指向的字串,根據引數base,按權轉化為long int, 然後返回這個值。引數base的範圍為2~36,和0;它決定了字串以被轉換為整數的權值。strtol()函式檢測到第一個非法字元時,立即停止檢測,其後的所有字元都會被當作非法字元處理。合法字串會被轉換為long int, 作為函式的返回值。非法字串,即從第一個非法字元的地址,被賦給*endptr。**endptr是個雙重指標,即指標的指標。strtol()函式就是通過它改變*endptr的值,即把第一個非法字元的地址傳給endptr。多數情況下,endptr設定為NULL, 即不返回非法字串。

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
<pre name="code" class="cpp">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