Use the stringstream of C ++ to convert various data types

Source: Internet
Author: User

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 );

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.