One, based on C++11 standard
Header file: #include <string>
function:
1.1 Value to string
to_string(val): Other types can be converted to string.
1.2 string conversion value
stoi(s, p, b): string to int
stol(s, p, b): string to long
stod(s, p, b):string转double
stof(s, p, b): string to float
stold(s, p, b):string转long dluble
stoul(s, p, b), stoll(s, p, b), stoull(s, p, b)等。
Remarks: return the value of the starting substring of s (a string representing the content of an integer); b represents the base used for conversion, and the default is 10 (representing decimal); p is a pointer to size_t, which is used to store the first non- The subscript of a numeric character, p is 0 by default, that is, the function does not return the subscript.
1 void testTypeConvert() 2 { 3 //int --> string 4 int i = 5; 5 string s = to_string(i); 6 cout << s << endl; 7 //double --> string 8 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; //自动转换成int类型的参数 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 }
Second, the version before C++11
The C++11 standard did not provide a corresponding method to call before, so you have to write the conversion method yourself. The code is as follows:
To convert from other types to string , define a method of a template class.
Convert from string to other types and define multiple overloaded functions.
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 }