Nukodi
Nukodi

Reputation: 357

How to format printf output

I have a for loop that prints out data from an array but I want them to print out so that they all line up neatly.

1.  123124124 24
2.  12412452  56
3.  12312     12
.
.
.
10. 12412412  12

I have printf("%d.%d%d\n", x, y, z); Any help is appreciated!

Upvotes: 0

Views: 1059

Answers (4)

Da Chen
Da Chen

Reputation: 33

use %-numd or %numd to control the output style.

The num means the width you want to have. Replace it by numbers, like: %-10d or %10d.

And - means left aligned. Without it, the output will be right aligned.

For examle: printf("%-5d%5d",123,456) then the output will be 123 456

Upvotes: 0

chux
chux

Reputation: 154601

OP's requested format is challenging as it wants a '.' immediately following the (int) x and then padded as needed.

@BLUEPIXY, as usual, offers a nifty solution. This takes advantage of the result of first printing x.

printf("%-*s%-9d%3d\n", 4-printf("%d", x), ".", y, z);

Alternative, convert to double.

"%-#3.0f Prints double, at least 3 characters, left justified, always with '.', no digits after the '.'.

//123 123456789 12
//10. 12412412  12
//1.  123124124 24
printf("%-#3.0f %-9d %d\n", (double) x, y, z);

Upvotes: 1

PL200
PL200

Reputation: 741

printf("%d. \t %d \t %d \n", x, y, z);

\t inserts a tab, which should align your code nicely.

Upvotes: 0

lost_in_the_source
lost_in_the_source

Reputation: 11237

printf("%-3d%-12d%d\n", x, y, z);

The number following the minus sign and preceeding the d is the minimum width of the field. For the count column, we want it to be at least 3 columns wide. However, we also want it to pad to the right, which is why the minus sign is used.

Same goes for the %-12d, except that the minimum width is 12. Have a look at this sample

http://codepad.org/jJA8v8v8

If you want the period, you're going to have to print that as a string with %s.

Upvotes: 3

Related Questions