Home > Software engineering >  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 ?

Time:10-14

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?

CodePudding user response:

printf accepts any string as its first argument, not just string literals. Just be careful that the format must match the arguments. That makes this rather error-prone. E.g. specifying %d and passing char is undefined behaviour.

int main(){
    std::string user_format = "%x";

    int x = 100;

    std::printf(user_format.c_str(),x);
}

std::hex and std::setprecision modifiers might be more suited for this task.

CodePudding user response:

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

2

  • provide user with a choice of predefined safe and applicable formatting options

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

  •  Tags:  
  • c
  • Related