C + + StringStream Clear () Erase error

Source: Internet
Author: User

When writing programs in C + +, it is often necessary to convert types such as int or double to string. For this operation, I often use the stringstream. Like what

Int  

Using this method, you can convert the value of type A to string type (in the same way, you can convert a type such as Double,long).

If you want to convert multiple variables of a type such as int/double, and always use a StringStream object (avoid the overhead of always creating stringstream), Then you need to empty the contents of StringStream before using StringStream again. The first thing we think about is the clear () method. After viewing StringStream really have a clear () method (Good happy ^.^), so you go to apply StringStream.

StringStream S1;int a = 10;double B = 2.8;s1 << a;string a_str = S1.str (); S1.clear (); s1<<b;string b_str = S1.s TR (); S1.clear (); cout << "a_str:" << a_str << "\ t b_str:" << b_str << Endl;


It turned out to be the result of the operation!!

A_str:10 b_str:102.8

What's going on!? The original clear () method simply resets the StringStream status flag and does not erase the data. If you need to clear the data, you can use the S1.str ("") to achieve this purpose.

Remember! Otherwise it is easy to make your program error, and eat your memory!

Reference: http://blog.163.com/[email protected]/blog/static/1408083742012214104532291/

C + + StringStream Clear () Erase error

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