Variable length space using printf
I'm trying to format some printf statements to allow for arbitrary levels of indentation. Ideally I want the fol开发者_运维技巧lowing 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.
You can just pass as a parameter what you want to printout:
printf( "%*s", indent_level + strlen(mystr), mystr );
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.
精彩评论