Jobs
Jobs

Reputation: 3377

C printf: variable string column width, left align

I'm trying to format printf string output:

printf("%*s %*s %*s %*s %*s %*s %*s %*s %*s\n", 
maxlen[0], "intf", maxlen[1], "ssid", maxlen[2], 
"bssid", maxlen[3], "vlan", maxlen[4], "STA", 
maxlen[5], "tx-pkts", maxlen[6], "rx-pkts", maxlen[7],
 "security", maxlen[8], "Capabilities");

where maxlen is an array with values 5, 13,17, 4, 3, 7, 7, 15, and 12 in this case.

However, in the output, the strings are right aligned, meaning they are floated to the right of their width-sized blocks. Output:

intf ssid bssid vlan STA tx-pkts rx-pkts security Capabilities

Is there a way to float these strings to the left?

So instead of [][][][][][][]security, I want security[][][][][][][]for the width==15second-to-last block, for example.

I tried creating a spacesarray of strings, like below:

char **spaces = (char**)malloc(9*sizeof(char*));

then, for each i, calloc spaces[i], and then, instead of doing "%*s", I do %s%s, where the second string printed is spaces[i].

But even this doesn't seem to work because I would need to do

snprintf(spaces[i], maxlen[i]-size_of_string, "  (however many spaces)    ");

And I don't know how many spaces to hardcode for the third argument. There is no " " * length operation like in python, to create a length sized string of " " characters.

Upvotes: 6

Views: 13931

Answers (1)

Weather Vane
Weather Vane

Reputation: 34585

To left-align the output in the width given, add a - sign to the format specifier

printf("%-*s %-*s %-*s %-*s %-*s %-*s %-*s %-*s %-*s\n", ... ); 

The arguments supplied for width can be a computed int value. You can hard-code the width like this

printf("%-10s\n", "string");

If you don't know how much space will be taken, you can use a temporary string

char tempstr[100];
int len = sprintf(tempstr, "%d", value);
printf("%s%-*s\n", tempstr, 30 - len, "string");

Upvotes: 12

Related Questions