How to format a string according to the formatting method entered by user in c++?

How to format a string according to the formatting method entered by user in c++?
For example, here is an integer:
int x = 100;
If a user inputs a formatting method (a string):
"%x"
I want to output: 0x40.

And another user inputs a formatting string:
%.4f,
I want it output:100.0000.
How to do it?

Answer

I see the following two concepts:

1.

  • read in the formatting string from the user
  • reject anything with more than one format specifier
  • reject anything with wrong format specifier for the type of the variable you want to output (using a float specifier for an integer for example would be wrong; just mentioning it specifically because your example looks like this….)
  • reject anything with the wrong format specifier for the width of the variable (same as above, just another detail)
  • reject wrong specifiers which do not attempt to output the variable (there are some fancy/dagerous things which could otherwise be done with a user-provided string…)
  • remove anything but the format specifier (assuming you mean to not allow “decoration”)
  • either reject above by removing it and use the remainder
  • or reject by giving an error message and asking for another input
  • use the string for output
  • provide user with a choice of predefined safe and applicable formatting options

For security and reliability reasons I would probably go with option 2.