C/C++中型別轉換
阿新 • • 發佈:2019-02-04
C/C++中經常會使用到基本資料型別與字串(char*)型別的相互轉換,我在這裡總結一下我學到的幾種轉換方法,歡迎補充和糾錯。
一. 從其他基本資料型別到字串
方法(1): 使用stdio.h庫中的snprintf函式, 將格式化字串寫到char陣列
原型:
int snprintf ( char * s, size_t n, const char * format, ... );
引數:
s : 目標字元陣列
n: 最大可以寫到s中的字元數(包含結尾'\0'字元)
format: 格式化字串
返回值:
成功時返回寫到字元陣列中的字元數(結尾的'\0'字元不算在裡面),失敗時返回負數
示例程式碼
char s[1000];
int n = snprintf(s, 1000,"%f %d %s", 0.33, 22, "hello");
printf("written char number: %d\nresult string: %s\n", n, s);
return 0;
優點:簡單直接
缺點:溢位時會發生截斷,而且還必須使用正確的格式化字串,否則會導致不可預知的結果。
方法二(2)使用<sstream>庫的stringstream 或ostringstream物件
a. stringstream物件可用於輸入和輸出流
b. ostringstream物件只用於輸出流
ostringstream示例程式碼:
ostringstream ostream;
ostream<<22<<" "<<0.33;
cout<<ostream.str()<<endl
stringstream示例程式碼:
stringstream stream;
stream<<22<<" "<<0.33;
cout<<stream.str()<<endl;
注意: str是stream物件的成員方法,它有以下兩個原型:
string str() const; void str (const string& s);
第二個原型會先清空當前流的內容,然後將s設定為當前流內容。
優點:由編譯器進行型別安全檢查,簡單又安全
缺點:stream物件的構造和析構耗費時間,但是可以通過使用clear後對stream物件進行復用來提高效率。
二. 從字串到其他基本資料型別
方法(1):使用<stdio.h>的sscanf函式,從給定字串格式化讀入資料<strong> </strong> int a;
double b;
char s[1000];
sscanf("12 33.33 hello", "%d%lf%s", &a, &b, &s);
cout<<a<<" "<<b<<" "<<s<<endl;
優點:簡單直接。 缺點:必須使用正確的格式化字串,否則會導致不可預知的結果。 方法(2): 使用<sstream>庫的stringstream 或istringstream物件
a. stringstream物件可用於輸入和輸出流
b. istringstream物件只用於輸入流
stringstream示例程式碼:
int a;
double b;
char s[1000];
stringstream stream("22 0.33 hello");
//or stream.str("22 0.33 hello");
stream>>a>>b>>s;
cout<<a<<" "<<b<<" "<<s<<endl;
istringstream示例程式碼:
int a;
double b;
char s[1000];
istringstream istream("22 0.33 hello");
//or stream.str("22 0.33 hello");
istream>>a>>b>>s;
cout<<a<<" "<<b<<" "<<s<<endl;
注意: (1)轉換時,每個物件都以空格或tab或換行符作為分割符。 (2)若要複用stringstream物件(每遇到一次作為輸入流然後緊接著再作為輸出流,那就是不同的兩次), 在這之間要呼叫clear成員函式。 方法(3):使用<stdlib.h>庫中的atoi、atol、strtod、strtof、strtol等,其中str開頭的函式還支援進位制轉換,還支援從任意字串轉換(也就是說字串不一定是純數字的)。