1

Is there a C/C++ library that can to formatting similar to printf with a format string, but which verifies if this format string satisfies certain constraints, and matches the arguments?

The reason is that the program should take a format string from user input, as a template for a series of file names, with one integer index variable. So the user could provide image%d.png or image%.6d.png, but hack_%d_%s would not be accepted.

2

The most immediate answer to your question is, I believe, tinyformat, which only aims to provide a typesafe printf() replacement and is in-use. I would not recommend you choose that one, though.

You would probably be better served by fmt, which has a wider scope but does more, has seen more development and is in wider use (there's also the older FastFormat). As you'll see at the links, they won't fail you like printf().

If you want the most bare-bones do-it-yourself thing possible, there's a variadic-template-based safe printf() implementation idea by C++ luminary Andrei Alexandrescu from 20120 - see this StackOverflow.com answer for details.


A final note outside the scope of OP's specific scenario: With C++17 it has becomes sort-of-possible to go even beyond all of these options and use constexpr format-string constants to do the verification completely at compile time rather than runtime, which would be awesome (assuming, of course, you know your format beforehand). Nothing like that has been released as of right now (that I know of).

2
  • How does constexpr format strings help OP, who wants to enter a format string from the keyboard?
    – Ira Baxter
    Mar 12 '17 at 7:59
  • @IraBaxter: It doesn't help in OP's specific case, but it does help in the general case represented by the question's title. I'll edit to clarify that.
    – einpoklum
    Mar 12 '17 at 9:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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