13

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.

0

2 Answers 2

18

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

printf( "%*s", indent_level + strlen(mystr), mystr );
Sign up to request clarification or add additional context in comments.

7 Comments

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.
You only have to know the length of the first parameter - e.g. you could use printf("%*d, %d, ...", indent_level, param1, ... )
I have first time seing that type usage of printf,can you explain why you are using indent_level+strlen(mystr)?
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 Hmm, I don't follow how printf( "%*d", indent_level, param ) will do what I want.
|
5

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.