<Sstream> in the C ++ Standard Library provides more advanced functions than <stdio. h> in ansi c, that is, simple, type-safe, and scalable. In this article, I will show how to use these libraries for secure and automatic type conversion.
Why Learning
If you are used to <stdio. h> style conversion, you may first ask: Why do you need to spend extra energy learning <sstream>-based type conversion? Maybe the review of the following simple example can convince you. Suppose you want to use the sprintf () function to convert a variable from the int type to the string type. To correctly complete this task, make sure that the target buffer zone has enough space to accommodate the converted string. In addition, the correct format character must be used. If incorrect formatting characters are used, unexpected consequences may occur. The following is an example:
Int n = 10000;
Chars [10];
Sprintf (s, "% d", n); // The content in S is "10000"
So far it looks good. However, a slight change to the code above will cause the program to crash:
Int n = 10000;
Char s [10];
Sprintf (s, "% F", n); // check! Incorrect formatting character
In this case, the programmer mistakenly uses the % F formatting character to replace % d. Therefore,SAfter calling sprintf (), it contains an uncertain string. If we can automatically export the correct type, isn't it better?
Enter stringstream
BecauseNAndSSo the compiler has enough information to determine which conversions are needed. <Sstream> the standard classes declared in the library take advantage of this and automatically select the necessary conversions. In addition, the conversion result is saved in the internal buffer of the stringstream object. You don't have to worry about Buffer Overflow because these objects will automatically allocate storage space as needed.
Does your compiler support <sstream>?
<Sstream> the library was recently included in the C ++ standard. (Do not confuse <sstream> with <strstream> that was deleted before the standard release .) Therefore, earlier compilers, such as gcc2.95, do not support it. If you happen to be using such a compiler and want to use <sstream>, you need to update it first.
<Sstream> the library defines three types: istringstream, ostringstream, and stringstream for stream input, output, and input/output Operations respectively. In addition, each class has a corresponding wide character set version. For simplicity, I focus on stringstream, because each conversion involves input and output operations.
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.
String to int Conversion
String result = "10000 ";
Int n = 0;
Stream <result;
Stream> N; // n equals 10000
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 using the same stringstream (instead of creating a new object each time) in Multiple conversions is efficiency. Stringstream Object Construction and destructor are usually very CPU-consuming.
Use template in type conversion
You can 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 valueTIs the to_string () function of the parameter. The to_string () function willTConvert to a string and write it into result. Use the STR () member function to obtain a copy of the internal buffer of the stream:
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 convert multiple numeric values into strings:
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"
Conclusion
In the previous program code and pure C Programs, the 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>. The <sstream> Library also provides another feature-scalability. You can use overload to support conversion between custom types.
Some instances:
Stringstream is usually used for data conversion.
Compared with the C-database conversion, it is more secure, automatic, and direct.
Example 1: Convert the basic data type from int to string
# Include <string>
# Include <sstream>
# Include <iostream>
Int main ()
{
STD: stringstream stream;
STD: String result;
Int I = 1000;
Stream <I; // input int streams
Stream> result; // extract the int value inserted earlier from stream
STD: cout <result <STD: Endl; // print the string "1000"
}
Running result:
Example 2: In addition to basic type conversion, char * conversion is also supported.
# Include <sstream>
# Include <iostream>
Int main ()
{
STD: stringstream stream;
Char result [8];
Stream <8888; // insert 8888 to stream
Stream> result; // extract the value from stream to result
STD: cout <result <STD: Endl; // The screen displays "8888"
}
Example 3: When performing multiple conversions, you must call the stringstream member function clear ().
# Include <sstream>
# Include <iostream>
Int main ()
{
STD: stringstream stream;
Int first, second;
Stream <"456"; // insert a string
Stream> first; // convert to int
STD: cout <first <STD: Endl;
Stream. Clear (); // You must clear the stream before performing multiple conversions.
Stream <true; // insert bool Value
Stream> second; // extract int
STD: cout <second <STD: Endl;
}
Result of running clear
No result for running clear