Reputation: 381
ive written a program that creates a table of random numbers and its supposed to print only the numbers that are greater then 67. I was able to do it but for the numbers that are not greater then 67 i would like to fill its position with spaces. for right now i just have 0's in there with "%-5d" but i would like that version to be translated into spaces. my table looks like this currently
0 56.75 0 34.65
0 0 0 0
so everything is aligned correctly. how do i put spaces in between instead of 0's?
Upvotes: 0
Views: 7125
Reputation: 29116
You can apply the field width to strings, even the empty string:
if (x > 67) {
printf("%*s", width, "");
} else {
printf("%*.2f", width, x);
}
Of course, if you know the field width, that's a bit of an overkill; just use
printf(" ");
(If there's more to your question, I seem to have missed it. Maybe I'm reading too much into it.)
Upvotes: 2
Reputation: 2865
Several options -
If your numbers are not very long, simply use TAB ("\t") instead of spaces after each number. If the number may be long, this will not always work, on the other hand, a trivial padding will probably not work as well.
You can calculate the number of spaces you need and do a simple for loop, or generate an appropriate printf formatting (see the accepted answer https://stackoverflow.com/questions/276827/string-padding-in-c)
Upvotes: 3