neuromancer
neuromancer

Reputation: 55499

How to format printf statement better so things always line up

I have this printf statement:

 printf("name: %s\t"
        "args: %s\t"
        "value %d\t"
        "arraysize %d\t"
        "scope %d\n",
         sp->name,
         sp->args,
         sp->value,
         sp->arraysize,
         sp->scope);

It's inside a for loop, so it's printing multiple lines for a list of pointers.

The problem is that if some of the things that are printed are longer or shorter, it causes things to not line up. How do I get it to always line up?

Upvotes: 2

Views: 7251

Answers (3)

Didier Trosset
Didier Trosset

Reputation: 37437

Use a specific number for the maximum length of the string, in this case, 12:

printf("name: %12s", sp->name);

Upvotes: 3

Michael Burr
Michael Burr

Reputation: 340218

Each conversion specifier can be given a field width which give the minimum number of characters that conversion will use. There are other flags and precision that can be used to control the output (for example with the %s conversion the precision item says how many characters maximum will be used).

printf("name: %20.20s\t"
        "args: %10.10s\t"
        "value %6d\t"
        "arraysize %6d\t"
        "scope %6d\n",
         sp->name,
         sp->args,
         sp->value,
         sp->arraysize,
         sp->scope);

Upvotes: 8

ryan_s
ryan_s

Reputation: 7954

Like dtrosset said:

printf("name: %12s\t"
       // etc...

Here is some documentation on printf format strings:

http://www.cplusplus.com/reference/clibrary/cstdio/printf/

Just make sure that the field width you specify is larger than whatever you expect to be printing. If you specify %2d, for instance, and then print 555, it will still print with 3 characters even though the rest of your fields are 2 characters, and it won't line up the way you want it to.

Upvotes: 3

Related Questions