1つは、C ++ 11標準に基づいています
ヘッダーファイル:#include <string>
関数:
1.1文字列への値
to_string(val):他のタイプは文字列に変換できます。
1.2文字列変換値
stoi(s、p、b):文字列からint
stol(s、p、b):文字列から長い
stod(s、p、b):string転ダブル
stof(s、p、b):フロートする文字列
stold(s、p、b):文字列回転長いdluble
stoul(s、p、b)、stoll(s、p、b)、stoull(s、p、b)等。
備考:s(整数の内容を表す文字列)の開始サブストリングの値を返します。bは変換に使用されるベースを表し、デフォルトは10(10進数を表す)です。pはsize_tへのポインターであり、最初の非-を格納するために使用されます。数字の添え字、pはデフォルトで0です。つまり、関数は添え字を返しません。
1 void testTypeConvert() 2 { 3 // int- > string 4 int i = 5; 5文字列s = to_string(i); 6 cout << s << endl; 7 // double->文字列 8double d = 3.14; 9 cout << to_string(d)<< endl; 10 // long- >文字列11long l = 123234567; 12 cout << to_string(l)<< endl; 13 // char->文字列 14char c = 'a'; 15 cout << to_string(c)<< endl; //自ω転换成intクラス型的参数 16 // char- > string 17 string cStr; cStr + = c; 18 cout << cStr << endl; 19 20 21 s = "123.257"; 24 // string- > long 25 cout << stol(s)<< endl; 26 // string- > float 27 cout << stof(s)<< endl; 28 //文字列-> doubel 29 cout << stod(s)<< endl; 30}
第二に、C ++ 11より前のバージョン
C ++ 11標準では、以前に呼び出す対応するメソッドが提供されていなかったため、変換メソッドを自分で作成する必要があります。コードは次のとおりです。
他のタイプから文字列に変換するには、テンプレートクラスのメソッドを定義します。
文字列から他のタイプに変換し、複数のオーバーロードされた関数を定義します。
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リターン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リターン値; 20} 21 22 double convertStringToDouble(const string&s) 23 { 24 double val; 25 std :: strstream ss; 26 ss << s; 27 ss >> val; 28リターン値; 30 31 long convertStringToLong(const string&s) 32 { 33 long val; 34 std :: strstream ss; 35 ss << s; 36 ss >> val; 37リターン値; 38} 39 40 void testConvert() 41 { 42 //他のタイプを文字列に変換する43cout << "他のタイプを文字列に変換する:" << endl; 44文字列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; 52 cout << "文字列から他のタイプに変換:" << 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}