C + + string stream Sstream (commonly used for format conversions)
Simplifying type conversions using StringStream objects
The <sstream> in the C + + standard library provides some of the more advanced features of <stdio.h> more than ANSI C, namely simplicity, type safety, and extensibility. In this article, I'll show you how to use these libraries for secure and automated type conversions.
Why to study
If you are used to the <stdio.h> style conversion, perhaps you first ask: why spend extra energy to learn the type conversion based on <sstream>? Perhaps a review of the following simple example can persuade you. Suppose you want to use the sprintf () function to convert a variable from an int type to a string type. To do this correctly, you must make sure that the target buffer has enough space to accommodate the converted string. In addition, you must use the correct format characters. If an incorrect format character is used, it can result in unintended consequences. Here is an example:
int n=10000;
CHARS[10];
sprintf (S, "%d", n);//s content 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);//Look! Malformed format character
In this case, the programmer mistakenly used the%f format character instead of%d. Therefore,s contains an indeterminate string after the sprintf () call is completed. Wouldn't it be better if you could deduce the correct type automatically?
Enter StringStream
BecauseNAndsType is determined at compile time, so the compiler has enough information to determine which transformations are required. The standard classes declared in the <sstream> library take advantage of this and automatically select the necessary transformations. Furthermore, the result of the conversion is stored in the internal buffer of the StringStream object. You don't have to worry about buffer overruns, because these objects automatically allocate storage space as needed.
does your compiler support <sstream>?
The <sstream> library has only recently been included in the C + + standard. (Do not confuse <sstream> with the <strstream> that was deleted before the standard was released.) As a result, older 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.
The <sstream> library defines three kinds: Istringstream, Ostringstream, and StringStream, respectively, for the input, output, and input and output operations of the stream. In addition, each class has a corresponding wide character set version. For simplicity's sake, I mainly focus on stringstream, because each transformation involves input and output operations.
Note,<sstream> uses a string object instead of a character array. This avoids the danger of buffer overflow. Also, the types of incoming and target objects are automatically deduced, even if incorrect format characters are used.
string-to-int conversion
String result= "10000";
int n=0;
stream<<result;
stream>>n;//n equals 10000.
Reusing StringStream objects
If you intend to use the same StringStream object in multiple conversions, remember to use the clear () method before each conversion;
The greatest benefit of reusing the same stringstream (instead of creating a new object each time) in multiple conversions is efficiency. The construction and destructor of StringStream objects is usually very CPU-intensive.
Using templates in type conversions
You can easily define a function template to convert an arbitrary type to a specific target type. For example, you need to convert various numeric values, such as int, long, double, and so on, to a string, using the to_string () function with a string type and an arbitrary value of T as the argument. The to_string () function converts t to a string and writes to result. Use the STR () member function to get a copy of the stream's internal buffer:
Template<class t>
void To_string (String & result,const t& T)
{
Ostringstream oss;//Create a stream
oss<<t;//to pass the value in a stream
Result=oss.str ();//Gets the converted character to go and writes it to result
}
In this way, you can easily convert a number of values 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
You can further define a generic transformation template for conversions between any type. The function template convert () contains two template parameters Out_type and In_value, which is the function of converting in_value values into Out_type types:
Template<class Out_type,class in_value>
Out_type CONVERT (const In_value & T)
{
StringStream stream;
stream<<t;//the value in the stream
Out_type result;//Store Conversion results here
stream>>result;//writing values to result
return result;
}
This uses convert ():
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 last program code and the pure C program, the traditional <stdio.h> form of conversion accompanies us for a long time. However, as described in the article, the StringStream-based conversion has a type-safe and does not overflow such eye-catching features that we have ample reason to abandon <stdio.h> and use <sstream>. The <sstream> library also provides another feature-extensibility. You can use overloads to support conversions between custom types.
Some examples:
StringStream are usually used for data conversion.
Compared to the C library conversion, it is more secure, automatic and straightforward.
Example one: Basic data type Conversion example int to string
#Include <string>
#Include <sstream>
#include <iostream>
Int main ()
{
std::stringstream stream;
std::string result;
int i = 1000;
stream << i; // the int input stream
stream >> result; //
Std::cout << result << std::endl; // print the string "
}
Operation Result:
Example two: the conversion of char * is supported in addition to the basic type of conversion.
#include <sstream>
#include <iostream>
Int main ()
{
std::stringstream stream;
char result[8] ;
stream << 8888; // insert 8888 in the stream; stream >> result; // extract values from stream to result
std::cout << result << std::endl; // screen display "8888" Span style= "color: #008000;" >
}
Example three: When you make 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 String
Stream >> first;// convert Int
std::cout << first << std::endl;
stream.clear (); // before making multiple conversions, you must clear Stream
Stream << true; // insert bool value
stream >> second; // extract Int
std::cout << second << std::endl;
}
Run the clear result
No results were run for clear
Note: The role of Stream.clear () and Stream.str ("") is unclear. Also said clear is the removal of the flag bit, str ("") is clear stream content. However, during the multiple conversion process, it is true that clear is used exactly, which is verified.
Use <sstream> replace <stdio.h>