C ++ inline string formatting and numerical conversion

C # has a nice static method

String.Format(string, params string[]); 

which returns a new line with the provided formatting and values. Is there an equivalent in C ++?

The reason is that I use log4cxx and want to use macros like

 LOG4CXX_DEBUG( logger, expr ); 

which uses a short circuit estimate so that expr is never computed if the DEBUG log level is not enabled.

Currently in C ++ I am doing it like this:

 CString msg; msg.Format( formatString, values... ); LOG4CXX_INFO( _logger, msg ); 

which defeats the goal, since I must first select and format the string, so the efficiency of the short circuit logic is not so high.

There is a similar problem when trying to do simple logging with numeric values. This will not compile:

 LOG4CXX_DEBUG( _logger, "the price is " + _some-double_); 

So I have to write something like this:

 CString asStr; asStr.Format( "%d", _some-double_ ); LOG4CXX_DEBUG( _logger, "the price is " + asStr ); 

that defeats the goal again.

I'm not a C ++ expert at all, so I hope more knowledgeable people can help.

+4
source share
5 answers

log4cxx accepts parameters similar to a stream, so you can write, for example:

 LOG4CXX_DEBUG( _logger, "the price is " << price ); 
+9
source

You can go back to C and use sprintf

 printf(stderr,"The Error(%d) happened(%s)\n",error,errmsg(error)); 

Boost also has a format.

 // iostream with boost::format std::cerr << boost::format("The Error(%d) happened(%s)\n") % error % errmsg(error); 

If you want to use a shortcut

 logger && (std::cerr << Stuff); // Where Stuff can be your boost::format 
+4
source

Using standard libraries, it is impossible to create a formatted string without any memory allocation on your part. The C ++ string class does not have a “format” function as such, so you must use a stringstream object to combine numbers with text, but this is due to the distribution of the object. When considering C functions such as sprintf , you need to preallocate the char array, since sprintf does not allocate any memory.

However, if there were a static function like " string::format ", I doubt that you would get most of the advantages compared to distributing the stringstream object yourself and manipulating it, given that the static function is most likely to do same in the background anyway.

+3
source

My favorite way to do inline builds is with the boost.format library. For instance:

 #include <boost/format.hpp> using namespace boost; LOG4CXX_INFO( _logger, str(format("cheese it %i, %g") % 1234 % 1.3) ); 

This is very convenient for using variable arguments during registration and macro functions.

+3
source

Either use the formatting formatting library, or manually create your own small version (for example, make_string here ).

+2
source

All Articles