Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set variable text column width in printf

Tags:

c

printf

size

In order to determine the size of the column in C language we use %<number>d. For instance, I can type %3d and it will give me a column of width=3. My problem is that my number after the % is a variable that I receive, so I need something like %xd (where x is the integer variable I received sometime before in my program). But it's not working.

Is there any other way to do this?

like image 482
Alaa M. Avatar asked Aug 18 '11 10:08

Alaa M.


People also ask

How do you specify printf width?

The field width can also be specified as asterisk (*) in which case an additional argument of type int is accessed to determine the field width. For example, to print an integer x in a field width determined by the value of the int variable w, you would write the D statement: printf("%*d", w, x);

What does %% mean in printf?

As % has special meaning in printf type functions, to print the literal %, you type %% to prevent it from being interpreted as starting a conversion fmt.

What is %d %f %s in C?

%s refers to a string %d refers to an integer %c refers to a character. Therefore: %s%d%s%c\n prints the string "The first character in sting ", %d prints i, %s prints " is ", and %c prints str[0].

Can you use a variable in printf?

Using printf function, we can print the value of a variable. In order to print the variable value, we must instruct the printf function the following details, 1. specify the format of variable.


2 Answers

You can do this as follows:

printf("%*d", width, value); 

From Lee's comment:
You can also use a * for the precision:

printf("%*.*f", width, precision, value); 

Note that both width and precision must have type int as expected by printf for the * arguments, type size_t is inappropriate as it may have a different size and representation on the target platform.

like image 108
Oliver Charlesworth Avatar answered Sep 18 '22 00:09

Oliver Charlesworth


Just for completeness, wanted to mention that with POSIX-compliant versions of printf() you can also put the actual field width (or precision) value somewhere else in the parameter list and refer to it using the 1-based parameter number followed by a dollar sign:

A field width or precision, or both, may be indicated by an asterisk ‘∗’ or an asterisk followed by one or more decimal digits and a ‘$’ instead of a digit string. In this case, an int argument supplies the field width or precision. A negative field width is treated as a left adjustment flag followed by a positive field width; a negative precision is treated as though it were missing. If a single format directive mixes positional (nn$) and non-positional arguments, the results are undefined.

E.g., printf ( "%1$*d", width, value );

like image 20
jetset Avatar answered Sep 20 '22 00:09

jetset