How To Invoke Variables To Specify Format Of printf In C Programming

Viewed 176

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.

3 Answers

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

Yes, you can build a format string dynamically:

char fmt[20];
int b;
char a[SOME_SIZE];
char c[SOME_SIZE];

...
sprintf( fmt, "%%4s%%4d %%8s\n" ); // need %% to print a literal %, so fmt will contain "%4s%4d %8s\n"
printf( fmt, a, b, c );

There are other ways of building a format string dynamically, this is just the most straightforward.

I have heard C programming uses different declaration for each of them; i.e. int or char.

Yes, each format specifier expects its corresponding argument to have the correct type. %d expects its corresponding argument to have type int, %s expects its argument to have type char *, etc. If they don't match, then the behavior is undefined and you'll likely get weird-looking output.

I could achieve my first purpose thanks to all your support.

I wrote such code below, using a Symbolic Constant or "char anyname[] = string".

#include <stdio.h>

#define FORMAT "%30s\n" 

int main()
{
    char c_string[] = "You Suceed!";

    printf(FORMAT, c_string);

    return 0;
}

/*
int main()
{
    char format[] = "%s\n"; 
    char c_string[] = "You Suceed!";

    printf(format, c_string);

    return 0;
}
*/

I appreciate all your suggestion!

Related