Mauricio De armas
Mauricio De armas

Reputation: 2289

How can I format a dynamic output to create a table in a printf

I have this big printf, tha fills with a file.

 printf("\n%s \t\t%s \t\t%s \t%s \t%s \t%s \t%s \t%s \t%s \t%s \t%s\n", instante, territorio, blancos, nulos, subscritos,elegidos,porcentaje, validos, votos, hondt, estimados);

The thing is that I need to format the alignment stdout because now is like this: enter image description here

Upvotes: 3

Views: 1024

Answers (2)

Shadowchaser
Shadowchaser

Reputation: 616

You can specify how many characters should be used and rest would be filled with spaces, %20s would give you 20 characters for instance, or %-20s if you want padding on the right side.

#include <stdio.h>

int main() {
    char *items[] = { "First", "Second one", "Third" };
    char *clients[] = { "Jon Doe", "Carol Anne", "Roscoe Williams" };

    printf("%-20s\t%-20s\n", "Item", "Client");

    for (int i = 0; i < 3; i++)
        printf("%-20s\t%-20s\n", items[i], clients[i]);
}

Upvotes: 4

log0
log0

Reputation: 10947

printf supports padding. You should pad left or right every column to a fixed size

print("%-10s", 'test')

Upvotes: 1

Related Questions