日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++ string与数值的转换

發(fā)布時間:2024/4/18 c/c++ 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++ string与数值的转换 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

一、基于C++11標準

  頭文件:#include <string>

  函數(shù):

  1.1 數(shù)值轉(zhuǎn)string

  to_string(val):可以將其他類型轉(zhuǎn)換為string。

  1.2 string轉(zhuǎn)數(shù)值

  stoi(s, p, b):string轉(zhuǎn)int

  stol(s, p, b):string轉(zhuǎn)long

  stod(s, p, b):string轉(zhuǎn)double

  stof(s, p, b):string轉(zhuǎn)float

  stold(s, p, b):string轉(zhuǎn)long dluble

  stoul(s, p, b), stoll(s, p, b), stoull(s, p, b)等。

  備注:返回s的起始子串(表示整數(shù)內(nèi)容的字符串)的數(shù)值;b表示轉(zhuǎn)換所用的基數(shù),默認為10(表示十進制);p是size_t的指針,用來保存s中第一個非數(shù)值字符的下標,p默認為0,即函數(shù)不返回下標。

1 void testTypeConvert()2 {3 //int --> string4 int i = 5;5 string s = to_string(i);6 cout << s << endl;7 //double --> string8 double d = 3.14;9 cout << to_string(d) << endl; 10 //long --> string 11 long l = 123234567; 12 cout << to_string(l) << endl; 13 //char --> string 14 char c = 'a'; 15 cout << to_string(c) << endl; //自動轉(zhuǎn)換成int類型的參數(shù) 16 //char --> string 17 string cStr; cStr += c; 18 cout << cStr << endl; 19 20 21 s = "123.257"; 22 //string --> int; 23 cout << stoi(s) << endl; 24 //string --> long 25 cout << stol(s) << endl; 26 //string --> float 27 cout << stof(s) << endl; 28 //string --> doubel 29 cout << stod(s) << endl; 30 }

二、C++11之前的版本

  C++11標準之前沒有提供相應(yīng)的方法可以調(diào)用,就得自己寫轉(zhuǎn)換方法了,代碼如下:

  從其它類型轉(zhuǎn)換為string,定義一個模板類的方法。

  從string轉(zhuǎn)換為其它類型,定義多個重載函數(shù)。

1 #include <strstream>2 template<class T>3 string convertToString(const T val)4 {5 string s;6 std::strstream ss;7 ss << val;8 ss >> s;9 return s; 10 } 11 12 13 int convertStringToInt(const string &s) 14 { 15 int val; 16 std::strstream ss; 17 ss << s; 18 ss >> val; 19 return val; 20 } 21 22 double convertStringToDouble(const string &s) 23 { 24 double val; 25 std::strstream ss; 26 ss << s; 27 ss >> val; 28 return val; 29 } 30 31 long convertStringToLong(const string &s) 32 { 33 long val; 34 std::strstream ss; 35 ss << s; 36 ss >> val; 37 return val; 38 } 39 40 void testConvert() 41 { 42 //convert other type to string 43 cout << "convert other type to string:" << endl; 44 string s = convertToString(44.5); 45 cout << s << endl; 46 int ii = 125; 47 cout << convertToString(ii) << endl; 48 double dd = 3.1415926; 49 cout << convertToString(dd) << endl; 50 51 //convert from string to other type 52 cout << "convert from string to other type:" << endl; 53 int i = convertStringToInt("12.5"); 54 cout << i << endl; 55 double d = convertStringToDouble("12.5"); 56 cout << d << endl; 57 long l = convertStringToLong("1234567"); 58 cout << l << endl; 59 }

?

總結(jié)

以上是生活随笔為你收集整理的C++ string与数值的转换的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。