Oneliner for dealing with strings in C++

Alec Jacobson

October 05, 2012

weblog/

I always end up clawing at my face whenever I have to deal with strings in C++. Here are two handy macros to make life a bit easier:
// http://stackoverflow.com/a/2433143/148668
// Suppose you have a function:
//   void func(const char * c);
// Then you can write:
//   func(C_STR("foo"<<1<<"bar"));
#define C_STR(X) static_cast<std::ostringstream&>(std::ostringstream().seekp(0) << X).str().c_str()
// Suppose you have a function:
//   void func(std::string c);
// Then you can write:
//   func(STR("foo"<<1<<"bar"));
#define STR(X) static_cast<std::ostringstream&>(std::ostringstream().seekp(0) << X).str()