运行代码为
1 /* 2 * main.cpp 3 * 4 * Created on: Apr 7, 2016 5 * Author: lizhen 6 */ 7 8 #include <iostream> 9 //#include "MySqrt.h" 10 #include <math.h> 11 #include <vector> 12 #include <typeinfo> 13 #include <exception> 14 #include <stdexcept> 15 #include<string.h> 16 #include<sstream> 17 #include<stdio.h> 18 19 20 using namespace std; 21 22 class Base{ 23 public: 24 Base(){ 25 cout<<"create the base"<<endl; 26 } 27 virtual ~Base(){ 28 cout<<"destroy the base"<<endl; 29 } 30 }; 31 class Derived: public Base{ 32 public: 33 Derived(){ 34 cout<<"derived is created"<<endl; 35 } 36 virtual ~Derived(){ 37 cout<<"Derived is destroying"<<endl; 38 } 39 }; 40 //double -->string 41 string doubleConverToString(double d){ 42 ostringstream os; 43 if(os << d) return os.str(); 44 return "invalid conversion"; 45 } 46 47 //string-->double 48 double stringConverTodouble(string str){ 49 istringstream iss(str); 50 51 double x; 52 if(iss >> x) return x; 53 return 0.0; 54 } 55 56 //c-function double-->string 57 string cfunctionDtoS(double d){ 58 char str[100]; 59 sprintf(str,"%.3lf",d); 60 return str; 61 } 62 //c-function string->double 63 double cfunctionStoD(string str){ 64 double dd; 65 sscanf(str.c_str(),"%lf",&dd); 66 return dd; 67 } 68 69 int main() { 70 //string-->char* 71 string str("string"); 72 char *p = const_cast<char *>(str.c_str()); 73 cout<<"string->char*"<<p<<endl; 74 75 //char* -->string 76 char *ch = const_cast<char *>("char");//warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]| 77 string chstr(ch); 78 cout<<"char * -->string"<<chstr<<endl; 79 80 //double&float --->string 81 double dd = 3.14; 82 string ddstr = doubleConverToString(dd); 83 cout<<ddstr<<endl; 84 85 //string--->double&float 86 string strp = "3.5555555555"; 87 double strdd = stringConverTodouble(strp); 88 cout<<strdd<<endl; 89 cout<<atof(strp.c_str())<<endl; 90 91 92 93 //c-function double->string 94 string ss = cfunctionDtoS(3.146789); 95 cout<<"ss"<<ss<<endl; 96 97 //c-function string->string 98 double cdd = cfunctionStoD("3.14259"); 99 cout<<cdd<<endl; 100 }