參考文獻:https://blog.csdn.net/jllongbell/article/details/79092891
C語言裏面常用的字符串和數字轉換函數是sscanf和sprintf
spritf (直觀理解:往字符串中寫)
sprintf函數原型爲 int sprintf(char *str, const char *format, …)
作用是格式化字符串,具體功能如下所示:
(1)將數字變量轉換爲字符串。
(2)得到整型變量的16進制和8進制字符串。
(3)連接多個字符串。
int main()
{
char str[256] = { 0 };
int data = 1024;
//將data轉換爲字符串
sprintf(str, "%d", data);
cout << str << endl;
//獲取data的16進製表示
sprintf(str, "0x%X", data);
cout << str << endl;
//獲取data的8進製表示
sprintf(str, "0%o", data);
cout << str << endl;
const char *s1 = "Hello";
const char *s2 = "world";
//連接字符串
sprintf(str, "%s %s", s1, s2);
cout << str << endl;
double a = 3.1415;
sprintf(str, "%.3lf", a);
cout << str << endl
}
運行結果:
sscanf (直觀理解:從字符串中讀取數據)
sscanf函數原型爲int sscanf(const char *str, const char *format, …) 將參數str的字符串根據參數format字符串來轉換並格式化數據,轉換後的結果存於對應的參數內。具體功能如下:
(1)根據格式從字符串中提取數據。如從字符串中取出整數、浮點數和字符串等;
(2)取指定長度的字符串
(3)取到指定字符爲止的字符串
(4)取僅包含指定字符集的字符串
(5)取到指定字符集爲止的字符串
int main(){
char s[15] = "123.432,432";
int n;
double f1;
int f2;
sscanf(s, "%lf,%d%n", &f1, &f2, &n);
cout<<f1<<" "<<f2<<" "<<n;
return 0;
}
運行結果:
這裏的11就是轉換的字符數。
——————————————————————————————————————————————————————
庫定義了三種類:istringstream、ostringstream和stringstream,分別用來進行流的輸入、輸出和輸入輸出操作。
1.stringstream::str(); returns a string object with a copy of the current contents of the stream.
2.stringstream::str (const string& s); sets s as the contents of the stream, discarding any previous contents.
3.stringstream清空,stringstream s; s.str("");
4.實現任意類型的轉換
template<typename out_type, typename in_value>
out_type convert(const in_value & t){
stringstream stream;
stream<<t;//向流中傳值
out_type result;//這裏存儲轉換結果
stream>>result;//向result中寫入值
return result;
}
int main(){
string s = "1 23 # 4";
stringstream ss;
ss<<s;
while(ss>>s){
cout<<s<<endl;
int val = atoi(s.c_str());
cout<<val<<endl;
}
return 0;
}
int main(){
string s = "1,23,#,4";
stringstream ss;
ss<<s;
while(getline(ss, s, ',')){ //getline()
cout<<s<<endl;
int val = atoi(s.c_str());
cout<<val<<endl;
}
return 0;
}
運行結果: