7

I know that using the %s format specifier and std::string like this leads to undefined behaviour:

std::string myString = "test";
printf("%s", myString);

But is it save to use the same specifier and a std::string with boost::format?

#include <boost/format.hpp>

int main() 
{
   std::string myString = "test";

   boost::format fmt("%s");
   fmt % myString;

   std::cout << fmt.str();

   return 0;
}

%s specifies a (const) char*, but I provide a std::string. Could this lead to UB too?

2
  • I may be missing the point, but why not pass std::string.c_str()?
    – Kevin Hsu
    May 20, 2012 at 8:43
  • 1
    Because I found a lot of those calls in some legacy code, and I am trying to decide whether I need to fix it or not. Also I would like to know how to use the %s specifier correctly in the future. May 20, 2012 at 8:45

1 Answer 1

9

It is safe to use %s with boost::format and std::string. In contrast to printf, the type character in the format string "does not impose the concerned arguments to be of a restricted set of types, but merely sets the flags that are associated with this type specification."

http://www.boost.org/doc/libs/1_49_0/libs/format/doc/format.html#printf_directives

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.