I want to create output like this using printf:
Name Available Required
------------- ----------------- ---------------
Something 10.1 GiB 2.3 GiB
But using the built-in spacing mechanism doesn't allow to add a measurement text (ie Gb) after the variable, before the space. The issue is that this text needs to be included in the spacing. I have tried
"%-12.1f GiB"
Which puts "GiB" after the spacing.
The printf
function won’t do this in one shot. Use an intermediate string.
double gigabytes_avail;
char buf[64];
snprintf(buf, sizeof(buf), "%.1f GB", gigabytes_avail);
printf("%-12s", buf);
If you are using Visual Studio and its compiler you may consider using sprintf_s()
instead of snprintf()
. They are not the same function, but sprintf_s()
is suitable here.
Alternatively, you can do the padding yourself, since printf
returns the number of characters written…
int column_width = 15;
double gigabytes_avail;
// Does not handle errors, printf may return -1.
int r = printf("%.1f GB", gigabytes_avail);
for (; r < column_width; r++) {
putchar(' ');
}
As a minor note, the symbol for gigabyte is GB, not Gb. Gigabit is Gbit.
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