I want to use variables to specify format of printf in C programming.
I am quite a C programming newbie, having practiced bash shell scritps though.
In bash scripts, I can use a variable to specify format of printf as one below.
#!/bin/bash
### Variable
format="%4s%4d %8s\n"
### Main
printf "$format" $1 $2 $3
Then, Is there similar way like the above in C programming?
Is it possible in C?
The strings for the printf format include characters and numbers.
I have heard C programming uses different declaration for each of them; i.e. int or char.
Is there similar way like the above [
format="%4s%4d %8s\n"] in C programming?
Is it possible in C?
Yes, several ways to both questions.
Among them, you can use sprintf() to prepare the buffer:
char format[80] = {0};//create editable char array
int a = 12;
char buf1[] = {"this is string 1"};
char buf2[] = {"this is string 2"};
sprintf(format, "%s", "%4s%4d %8s\n");
printf(format, buf1, val, buf2);
Even closer to what you have done in your example ( format="%4s%4d %8s\n" ), you can simply define format as a string literal:
char *format = "%4s%4d %8s\n";//string literal not editable
Or, create an initialized, but editable char array
char format[] = {"%4s%4d %8s\n"};//editable, but only up to
//strlen("%4s%4d %8s\n");
//(+ NULL, which is implied when using "...".)
Note that C also provides a built in feature to enable run-time setting of precision when outputting floating point numbers:
double val = 22.123445677890;
int precision = 3;
printf("%.*f", precision , val);
Will output 22.123
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