STD: string is library type, and INT and double are built-in type.
Method 1: use function template to convert int to STD: string and double to STD: string.
Code
# Include < Iostream >
# Include < Sstream >
# Include < String >
Using NamespaceSTD;
template class T >
void convertfromstring (T & , const STD: string & );
Template<ClassT>
StringConverttostring (t );
IntMain (){
StringS ("123");
StringS1;
// convert STD :: string to int, double
int I = 0 ;
convertfromstring (I, S);
cout I Endl;
double d = 0 ;
convertfromstring (D, S);
cout d Endl;
// convert int, double to STD :: string
int I1 = 123 ;
S1 = converttostring (I1 );
cout S1 Endl;
DoubleD1= 123.123;
S1=Converttostring (D1 );
Cout<S1<Endl;
// In addition to converting basic types, stringstream also supports conversion of char *.
Stringstream stream;
Char Result [ 8 ];
Int I2 = 8888 ;
Stream < I2; // Insert 8888 to stream
Stream > Result; // Extract values from stream to result
Cout < Result < Endl; // Screen Display "8888"
// When performing multiple conversions, you must call the stringstream member function clear ()
Int Second;
Stream. Clear (); // You must clear the stream before performing multiple conversions.
Stream < True ; // Insert bool Value
Stream > Second; // Extract int
Cout < Second < Endl;
Return 0;
}
template class T >
void convertfromstring (T & value, const string & S) {
stringstream SS (s );
SS >> value;
}
Template<ClassT>
StringConverttostring (T value ){
Stringstream SS;
SS<Value;
ReturnSS. STR ();
}
Method 2: Convert c_str () into a C string and use atoi () and atof ().
Code
# Include < Iostream >
# Include < String >
# Include < Cstdlib >
Using Namespace STD;
Int Main (){
String S = " 123 " ;
Double N = Atof (S. c_str ());
// Int n = atoi (S. c_str ());
Cout < N < Endl;
}