The C ++ library defines three types: istringstream, ostringstream, and stringstream for stream input, output, and input/output Operations respectively. With the input of these three classes, the output operation can easily convert the data type.
Use input operations to Change Data Types
Istringstream stream;
String result = "123456 ";
Int n = 0;
Stream <result; // input from a string
Stream> n; // output to int
N is 123456.
You can use a template to make it more generic.
Template
DataType CExp (const char * lpsz)
{
DataType ret;
Assert (lpsz! = NULL );
Const std: string str (lpsz );
Std: istringstream istr (str );
Istr> ret;
Return ret;
}
The output operation can convert various types to strings.
The following is an implementation template
Template
String CStr (const DataType & data)
{
Std: ostringstream ostr;
Ostr <data;
Return ostr. str ();
}
Instance used:
Int I = 0;
I = CExp ("1234 ");
Cout <"I =" <I <endl;
String strConv;
StrConv = CStr (1234 );