Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C printf: Is there a way to add text after variable and before spacing?

Tags:

c

printf

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.

like image 750
Tobias S Avatar asked Jan 25 '23 23:01

Tobias S


1 Answers

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.

like image 164
Dietrich Epp Avatar answered Jan 30 '23 08:01

Dietrich Epp