could anyone tell me or point me to a simple example of how to append an int to a stringstream containing the word "Something" (or any word)?
Asked
Active
Viewed 3.4k times
14
3 Answers
18
stringstream ss;
ss << "Something" << 42;
For future reference, check this out.

Daniel A. White
- 187,200
- 47
- 362
- 445
3
I'd probably do something on this general order:
#include <string>
#include <sstream>
#include <iostream>
int main() {
std::stringstream stream("Something ");
stream.seekp(0, std::ios::end);
stream << 12345;
std::cout << stream.str();
return 0;
}
With a normal stream, to add to the end, you'd open with std::ios::ate
or std::ios::app
as the second parameter, but with string streams, that doesn't seem to work dependably (at least with real compilers -- neither gcc nor VC++ produces the output I'd expect when/if I do so).

Jerry Coffin
- 476,176
- 80
- 629
- 1,111
-
@hassan: no, stringstream has no c_str() method – Frunsi Jan 14 '10 at 17:46
-
-1 The output produced is `12345hing`, as the initialization of a `std::stringstream` object without setting the position at which to start writing will cause any input to be written at the beginning of the stream buffer. – Rubens Feb 28 '13 at 23:20
1
If you are already using boost, it has lexical_cast that can be be used for this. It is basically a packaged version of the above, that works on any type that can be written to and read from a stream.
string s("something");
s += boost::lexical_cast<string>(12);
Its probably not worth using if you aren't using boost already, but if you are it can make your code clearer, especially doing something like
foo(string("something")+boost::lexical_cast<string>(12));

KeithB
- 16,577
- 3
- 41
- 45