代码:
1 #include <iostream> 2 #include <string> 3 #include <sstream> //for istringstream 4 #include <iomanip> //for setprecision 5 #include <cstdio> //for sscanf 6 using namespace std; 7 8 int main() 9 { 10 cout << "/************string to double************/" << endl; 11 /************string to double************/ 12 string str = "12.34567890e2"; 13 cout << "string: "<<str << endl; 14 15 //using std::stod 16 double d; 17 string::size_type size; //13 18 d = stod(str, &size); //1234.56789 19 cout << "double value get by stod: " << setprecision(14) << d << ", size:"<<size << endl; //Note: must setprecision to see entire value 20 21 //using sstream 22 istringstream istrStream(str); 23 istrStream >> d; //1234.56789 24 cout << "double value get by istringstream:" << setprecision(14) << d << endl; 25 26 //using sscanf 27 int len; //13 28 sscanf_s(str.c_str(), "%14lf%n", &d, &len); //1234.56789 29 cout << "double value get by sscanf: " << setprecision(14) << d <<", size:"<<len<< endl; 30 31 32 cout << "\n\n/**************double to string***************/" << endl; 33 /**************double to string***************/ 34 double d8 = 1.123456789e2; 35 cout << "double value: " << setprecision(14) << d8 << endl; 36 37 string str8 = std::to_string(d8);//112.345679 38 cout << "string get by std::to_string: " << str8 << endl; 39 40 ostringstream ostrStream; 41 ostrStream << setprecision(10); 42 ostrStream << d8; 43 str8 = ostrStream.str();//112.3456789 44 cout << "string get by ostringstream: "<< str8 << endl; 45 46 char ch[64]; 47 sprintf_s(ch, "%g", d8); 48 str8 = ch;//112.346 49 cout << "string get by sprintf: " << str8 << endl; 50 51 //below code is used to avoid control exit quickly 52 char c; 53 cin >> c; 54 55 return 0; 56 }
结果: