views:

258

answers:

3

Hello, 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)?

Thanks!

+8  A: 
stringstream ss;
ss << "Something" << 42;

For future reference, check this out.

http://www.cplusplus.com/reference/iostream/stringstream/

Daniel A. White
+1  A: 
#include <string>
#include <sstream>
#include <iostream>

int main() {      
    std::stringstream stream("Something ");

    stream << 12345;

    std::cout << stream.str();
    return 0;
}
Jerry Coffin
`c_str()` is wrong, should be `std::cout << stream.str();`
frunsi
@hassan: no, stringstream has no c_str() method
frunsi
Thanks Neil -- stupid slipup on my part.
Jerry Coffin
A: 

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