Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Quick and convenient way to build STL strings.

0.00/5 (No votes)
9 Jul 2013 1  
A quick and convenient way to build STL strings.

Introduction

This is probably one of the shortest articles you'll ever see on Code Project but the one line (!) of code presented here I find so insanely handy, I thought that I'd share it with y'all. That, and I wanted to get my article count up a bit :-)

stringstream's are really useful for building strings. No more sprintf buffer overruns or tediously trying to match up parameters with their placeholders in the format string. As an example, this is how you would use one:

#include <sstream>

int theAnswer = 42 ;

// build the string 
std::ostringstream buf ; 
buf << "The answer is: " << theAnswer ;
std::string str = buf.str() ;

cout << "My string = " << str << endl ; 

But I find it tedious to create the stringstream variables all the time, especially if there are several of them in the same scope since you have to give each one a unique name. So I wrote the following macro:

#define MAKE_STRING( msg )  ( ((std::ostringstream&)(std::ostringstream() 
    << msg)).str() )

It creates a temporary stringstream object, streams in the message and returns the string buffer when it's done. Note that the cast is necessary since operator<<() returns a reference to an ostream but we need an ostringstream to get at the underlying string buffer. You would use it like this:

std::string str = MAKE_STRING( "The answer is: " << theAnswer ) ;

It becomes even handier when you only want a temporay string object e.g.

extern void processString( const std::string& ) ;

processString( MAKE_STRING( "The answer is: " << theAnswer ) ) ;

I also have a version that returns the C-style char* pointer if that's what you need:

#define MAKE_CSTRING( msg )  ( ((std::ostringstream&)
    (std::ostringstream() << msg)).str().c_str() )

char buf[ 1024 ] ; 
strcpy( buf , MAKE_CSTRING("The answer is: " << theAnswer) ) ;

The only thing you need to watch here is that the char* pointer returned is a pointer to a temporary object. So in the example above, it's OK since the string object will stay alive until the call to strcpy() returns. But this is wrong:

const char* pDontTryThisAtHome = MAKE_CSTRING( 
    "The answer is : " << theAnswer ) ; 
printf( "%s\n" , pDontTryThisAtHome ) ;

Conclusion

And that's it! Article count: 2.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here