stringstream clearing question

May 11, 2012 at 10:08am
Since I'm one of those dodgy programmers who uses C + classes, I loiter here in an attempt to be fully converted to C++, you’ll be glad to hear it’s working, all be it a little slowly 8-)

Working with stringstreams I've found to be nice in the way of adding all sorts of types to a string ready to print or output to a file, however when say, assembling separate lines of text to be displayed, it would be nice to clear the stream last displayed and start adding to a new line of text (reusing the stream from empty) but there appears to be no member function to do this? Am I misusing stringstreams (ie there's something better for what I'm doing) or is it really the case of using the rather hackish method?

s.str("");

Your advice as always appreciated.
May 11, 2012 at 10:20am
Last edited on May 11, 2012 at 10:21am
May 11, 2012 at 10:27am
well that's what I would have thought, but that clears error states, not the contents of the stream.
May 11, 2012 at 10:31am
Usually simple string concatenation and to_string/lexical_cast-like functions are far more convenient than stringstreams, especially for simple cases, e.g.:
setText("Status: "+to_string(status));

And no, there's no easier way to reset a stringstream.
May 11, 2012 at 11:03am
Thanks Athar, really wanted to check I wasn't breaking anything with the str("") bit. So it's ok to do, just seems a bit odd.

I guess with the to_string function you mean write a function to take a value and return a string as the only to_string function I can find is for bit_set? Anyway, it's probably a good excercise for writing a template function taking different types?

May 11, 2012 at 11:06am
std::to_string is in C++11. If your implementation doesn't have it yet you can do as you said. Writing the function with templates using stringstream inside is not very hard.
Last edited on May 11, 2012 at 11:07am
May 11, 2012 at 11:09am
Also, lexical_cast is a function template in boost that allows you to convert to and from strings:
http://www.boost.org/doc/libs/1_49_0/doc/html/boost_lexical_cast.html
Last edited on May 11, 2012 at 11:10am
May 11, 2012 at 11:10am
Yep, I agree, ended up with this which works fine for my needs, thanks all.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
template <class myType>
inline std::string to_string( myType v )
{
    std::ostringstream oss;
    oss << v ;
    return oss.str() ;
}

main(...)
{
	std::string txt;
	int vali = 65;
	float valf = 66.43;
	txt = "int value is ";
	txt += to_string( vali );
	txt += " float value is ";
	txt += to_string( valf );

}
Topic archived. No new replies allowed.