Is there a quick, easy way of getting sprintf-like formatting when constructing a std::string? Something like...
std::string foo("A number (%d) and a character (%c).\n", 18, 'a');
                The Format specifier is a string used in the formatted input and output functions. The format string determines the format of the input and output. The format string always starts with a '%' character. The commonly used format specifiers in printf() function are: Format specifier.
%d is print as an int %s is print as a string %f is print as floating point.
The f in printf stands for formatted, its used for printing with formatted output.
%3d can be broken down as follows: % means "Print a variable here" 3 means "use at least 3 spaces to display, padding as needed" d means "The variable will be an integer"
Not built into the string's constructor, but you might want to check out boost format. Its a more typesafe sprintf style string formatting. With it you can at least do this:
std::string foo = 
    boost::str(boost::format("A number (%d) and a character (%c)\n") % 18 % 'a');
                        I've written a stringbuilder class which you can use and I think that is better than boost::format as unlike it, stringbuilder does NOT use C-style format string like %d, %c. etc.
Here is how stringbuilder can help you in just one line:
std::string s=stringbuilder() << "A number " << 18 <<" and a character " <<'a';
The implementation of stringbuilder is very simple:
struct stringbuilder
{
   std::stringstream ss;
   template<typename T>
   stringbuilder & operator << (const T &data)
   {
        ss << data;
        return *this;
   }
   operator std::string() { return ss.str(); }
};
Demo at ideone : http://ideone.com/J9ALB
I've just written the following blog describing the many different ways of the use of stringbuilder.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With