tags:

views:

84

answers:

1

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.

+5  A: 

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

printf( "%*s", indent_level + strlen(mystr), mystr );
adamk
Good suggestion, but the output string is also of variable length:printf( "%*s%d, %d, %d, %s, CONSTANT CHARS, %p\n", indent_level, "", ... );It's a pain to determine the length of that string without using an intermediate buffer.
210
You only have to know the length of the first parameter - e.g. you could use printf("%*d, %d, ...", indent_level, param1, ... )
adamk
I have first time seing that type usage of printf,can you explain why you are using indent_level+strlen(mystr)?
gcc
From printf's manpage: The field width: An optional decimal digit string (with non-zero first digit) specifying a minimum field width. Instead of a decimal digit string one may write "*" or "*m$" (for some decimal integer m) to specify that the field width is given in the next argument.
adamk
@adamk Hmm, I don't follow how printf( "%*d", indent_level, param ) will do what I want.
210
e.g. if the first parameter is some kind of timestamp (seconds since the epoch), you could write printf("%*d", indent_level + 10, timestamp) - this is because the timestamp is always 10 digits long (at least, for a very long foreseeable future). Of course, if the first parameter is also variable-length, then this won't work for you...
adamk
"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.
210