Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quick formatted strings in C++

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');
like image 251
slezica Avatar asked Apr 16 '11 12:04

slezica


People also ask

What is formatted string in C?

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.

What is %d %s %F in C?

%d is print as an int %s is print as a string %f is print as floating point.

What is %f in printf in C?

The f in printf stands for formatted, its used for printing with formatted output.

What does %3f mean in C?

%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"


2 Answers

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');
like image 164
Doug T. Avatar answered Oct 14 '22 22:10

Doug T.


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.

  • Create string on the fly just in one line
like image 38
Nawaz Avatar answered Oct 14 '22 22:10

Nawaz