Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable length space using printf

Tags:

c

printf

I'm trying to format some printf statements to allow for arbitrary levels of indentation. Ideally I want the following output where "One", "Two", etc are placeholders for variable length log messages.

One
 Two
  Three
 Two
One

I'm working on the variable length spacing required for the indentation, and I know I can do the following:

printf( "%*s", indent_level, "" );

but I'm wondering if there's a way to do it without the second empty string arg.

like image 252
bvanvugt Avatar asked Jul 09 '10 16:07

bvanvugt


2 Answers

You can just pass as a parameter what you want to printout:

printf( "%*s", indent_level + strlen(mystr), mystr );
like image 175
adamk Avatar answered Nov 08 '22 00:11

adamk


Can't write a comment for some reason, so posting as a separate necro-answer.

>> "Of course, if the first parameter is also variable-length, then this won't work for you"

> Yeah, that's the case; it needs to be able to handle a numeric value as the first param.

You can use a dud string

printf ("%*s%d", indent_level, "", decimal);

in order to indent variable-length decimals. A bit clunky, but works.

like image 21
undercat Avatar answered Nov 08 '22 01:11

undercat