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