OK, this really shouldn't be difficult, but after several attempts, I didn't find any solution.
How can one go about passing a formatted string to a function in 1 line? I want to have a simple method that I can use for logging/debugging purposes, something like this:
void debug(string s){
if (DEBUG) cerr << s;
}
I would like to be able to send formatted strings to this function, something like this:
debug("reading %s" % fname);
My main goal is to put as much functionality in the debug method so I can make life somewhat easier whenever I want to write stuff to stderr.
printf solutions seem to need a lot of code for simple formatting and boost::format seems to return some vague type that cannot be easily used as an argument without always including some .str() stuff.
Am I too lazy to be a C++ programmer or is there a neat way of accomplishing this goal that I have yet to discover?
You can define a macro around fprintf using __VA_ARGS__:
#define DBGLOG(format, ...) if(DEBUG){ fprintf(stderr, "%s -- %d -- ", __FUNCTION__, __LINE__); fprintf(stderr, format, ##__VA_ARGS__);}
This will, if DEBUG is true, output the function name and line number followed by whatever you wanted to print.
ex:
DBGLOG("%d\n", some_integer);
This will prepend the function and line number to the integer value and print it out.
You can write a function that takes in the format and passes it to your other function:
void debug( std::string s )
{
if (DEBUG) cerr << s;
}
void debug( boost::format format )
{
debug( format.str() );
}
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