Convert string and various built-in data types with standard C ++

Source: Internet
Author: User
To convert string to various built-in data types using standard C ++ Stringstream Category. This class is in the <sstream> Header File Medium Definition , <Sstream> Library Definition Three types: istringstream, ostringstream, and stringstream are used for stream input, output, and input/output Operations respectively. In addition, each class has a corresponding width. Character Set version. For simplicity, I focus on stringstream, because each conversion involves input and output operations. Example 1 demonstrates how to use a stringstream Object From
Note: <sstream> uses a String object instead of a character array. This avoids the risk of buffer overflow. In addition, the input parameters and the type of the target object are automatically derived, even if incorrect formatting characters are used, there is no danger.
Example 1:
STD: stringstream stream;
String result = "10000 ";
Int n = 0;
Stream <result;
Stream> N; // n equals 10000
Int to string type conversion
String result;
Int n = 12345;
Stream <N;
Result = stream. STR (); // result is equal to "12345"
Reuse stringstream object
If you want to use the same stringstream object in Multiple conversions, remember to use the clear () method before each conversion, the biggest benefit of repeatedly using the same stringstream object in Multiple conversions is that Efficiency . Stringstream Object Construction and Analysis Function It usually takes a lot of CPU time. After testing, using clear () alone cannot clear the content of the stringstream object, but only the status of the object. to reuse the same stringstream object, you must use STR () reinitialize the object.
Example 2:
STD: stringstream strsql;
For (INT I = 1; I <10; ++ I)
Strsql <"insert into test_tab values (";
Strsql <I <"," <(I + 10) <");";
STD: String STR = strsql. STR (); // obtain the string
Res = sqlite3_exec (PDB, str. c_str (), 0, & errmsg );
STD: cout <strsql. STR () <STD: Endl;
Strsql. Clear ();
Strsql. STR ("");
Used in conversionTemplate
You can also easily define a function template to convert any type to a specific target type. For example, you need to convert a variety of numeric values, such as int, long, and double, to a string, you need to use a string type and an arbitrary value T Is the to_string () function of the parameter. The to_string () function will T Convert to a string and write it into result. Use STR () Member Function to obtain a copy of the buffer inside the stream:
Example 3:
Template <class T>
Void to_string (string & result, const T & T)
Ostringstream OSS; // create a stream
OSS <t; // transmits the value as in the stream
Result = oss. STR (); // get the converted character and write it to result
In this way, you can easily add a variety of clothes Value Converted to a string:
To_string (S1, 10.5); // double to string
To_string (S2, 123); // int to string
To_string (S3, true); // bool to string
A general conversion template can be further defined for conversion between any types. The function template convert () contains two template parameters: out_type and in_value. The function is to convert in_value to out_type:
Template <class out_type, class in_value>
Out_type convert (const in_value & T)
Stringstream stream;
Stream <t; // value transmitted to the stream
Out_type result; // The Conversion Result is stored here.
Stream> result; // write a value to the result.
Return result;
Use convert () as follows ():
Double D;
String salary;
String S = "12.56 ";
D = convert <double> (s); // d equals 12.56
Salary = convert <string> (9000.0); // salary equals "9000"

In the pastProgramCodeAnd pure CProgramThe transformation of the traditional <stdio. h> form has been with us for a long time. However, as described in this article, the stringstream-based conversion has a type security and does not overflow this eye-catching feature, so we have ample reason to discard <stdio. h> and use <sstream>.
Of course, there is still a better choice, that is, to useBoostLexical_cast in the library, which is a type-safe conversion. For example:
# Include <iostream>

# Include <sstream>
# Include <string>
# Include <cstdlib>
# Include <boost/lexical_cast.hpp>
Using namespace STD;
Using namespace boost;
Int main (void)
Try {

// The following is a solution for converting built-in types to strings.

// Lexical_cast has obvious advantages

Int ival;

Char cval;

Ostringstream out_string;

String str0;

String str1;

Ival = 100;

Cval = 'W ';

Out_string <ival <"" <cval;

Str0 = out_string.str ();

Str1 = lexical_cast <string> (ival)

+ Lexical_cast <string> (cval );

Cout <str0 <Endl;

Cout <str1 <Endl;

// The following is a string-to-built-in conversion solution

// Compared to stringstrem, lexical_cast is of type security,

Int itmpe;

Char ctmpe;

Str0 = "100 K ";

Str1 = "100 h ";

Istringstream in_string (str0 );

In_string> itmpe> ctmpe;

Cout <itmpe <"" <ctmpe <Endl;

Itmpe = lexical_cast <int> (str1 );

Ctmpe = lexical_cast <char> (str1 );

System ("pause ");

Return 0;
Catch (bad_lexical_cast E)

Cout <E. What () <Endl;

Cin. Get ();

Related Article

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: 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.