How to use Ostringstream

Source: Internet
Author: User

How to use Ostringstream

"This article comes from" http://www.builder.com.cn/2003/0304/83250.shtml
Http://www.cppblog.com/alantop/archive/2007/07/10/27823.html
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 to achieve security and self-motivated type conversions.

Why to study

Assuming that you are used to the <stdio.h> style conversion, you may first ask: why spend extra effort to learn the type conversion based on <sstream>? Perhaps the recollection of one of the following simple examples can persuade you. Suppose you want to use the sprintf () function to convert a variable from an int type to a string type. In order to complete this task 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. Assuming that an incorrect format character is used, it can cause unintended consequences. Here's a sample:

int n=10000;

CHARS[10];

sprintf (S, "%d", n);//s content is "10000"

It looks pretty good up to now. However, a slight change to the above code will cause the program to crash:

int n=10000;

Char s[10];

sprintf (S, "%f", n);//Look! Malformed format character

In this case, the program ape mistakenly used the%f format character instead of%d. Therefore,s includes an indeterminate string after the sprintf () call is completed. Wouldn't it be better to be able to deduce the right type on your own initiative?

Enter StringStream

Because the types of n and s are determined at compile time, the compiler has enough information to infer which transformations are required. The standard class declared in the <sstream> library takes advantage of this and proactively chooses the necessary transformations. Also, 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 will have to allocate storage space on their own initiative.

Does your compiler support <sstream>?

<sstream> libraries are only recently 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 this 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 number. For simplicity's sake, I mainly focus on stringstream, because each conversion involves input and output operations.

Note,<sstream> uses a string object to replace the character array. This avoids the danger of buffer overflow. Also, the types of incoming and target objects are self-derived, even if the wrong format character is used.

string-to-int conversion

String result= "10000";
int n=0;
stream<<result;
stream>>n;//n equals 10000.

Reuse StringStream Objects

Suppose you intend to use the same StringStream object in multiple conversions, remember to use the clear () method before each conversion;

The greatest advantage of using the same stringstream repeatedly (instead of creating a new object each time) in multiple conversions is efficiency. The construction and destructor of StringStream objects is usually CPU-intensive.

Using templates in type conversions

You can easily define a function template to convert a random 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 a to_string () function that takes a string type and a random value of T as the parameter. 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 multiple 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

The ability to further define a generic transformation template for conversions between arbitrary types. 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 very long time. However, as described in the article, the StringStream-based conversion has a type-safe and does not overflow such eye-catching features, so that we have sufficient reason to abandon <stdio.h> and use <sstream>. The <sstream> library also provides another feature-extensibility. You can use overloads to support conversions between types that you define.

Some examples:

StringStream is generally used for data conversion.

Compared to C-Library conversion, it is more secure, self-motivated and direct.

Example one: Basic data type conversion sample 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; Extracts the previously inserted int value from the stream
Std::cout << result << Std::endl; Print the string "1000"
}

Execution Result:

Example two: the conversion of char * is supported in addition to the basic type conversion.

#include <sstream>
#include <iostream>

int main ()
{
Std::stringstream stream;
Char Result[8];
Stream << 8888; Inserting 8888 into the stream
Stream >> result; Extracts a value from a stream to result
Std::cout << result << Std::endl; The screen displays "8888"
}

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 to int
Std::cout << first << Std::endl;
Stream.clear (); You must clear the stream before making multiple conversions
Stream << true; insert BOOL Value
Stream >> second; Extract an int
Std::cout << second << Std::endl;
}

Perform a clear result

No clear results were performed

How to use Ostringstream

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.