In C++11, is there an easy (or even better, built-in) way to do something like this to do printf-style strings in an exception?
throw std::runtime_error( "Failed to open '%s' [%d]: %s",
filename, errno, strerror(errno) );
I know I could snprintf
to a `char []' then pass the result into an exception constructor with or w/o converting to std::string first.
Just wondering if C++11 has anything better/simpler to offer.
C++ printf is a formatting function that is used to print a string to stdout. The basic idea to call printf in C++ is to provide a string of characters that need to be printed as it is in the program.
printf() is a C function and therefore cannot and does not throw C++ exceptions; that is why a C++ style try/catch won't help.
The Printf module API details the type conversion flags, among them: %B: convert a boolean argument to the string true or false %b: convert a boolean argument (deprecated; do not use in new programs).
Syntax: int sprintf(char *str, const char *string,...); Return: If successful, it returns the total number of characters written excluding null-character appended in the string, in case of failure a negative number is returned .
Since C++11, you can construct exceptions from an std::string
:
std::runtime_error("Failed to open " + std::string(filename) + std::to_string(errno));
This has the slight drawback that the constructor of std::string
might throw
and thus terminate your program. However, this should only come into play while handling some kind of "out of memory" exception.
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