C语言 使用printf的可变长度空间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3214805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Variable length space using printf
提问by bvanvugt
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.
我正在尝试格式化一些 printf 语句以允许任意级别的缩进。理想情况下,我想要以下输出,其中“一”、“二”等是可变长度日志消息的占位符。
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.
但我想知道是否有办法在没有第二个空字符串 arg 的情况下做到这一点。
回答by adamk
You can just pass as a parameter what you want to printout:
您可以将要打印的内容作为参数传递:
printf( "%*s", indent_level + strlen(mystr), mystr );
回答by undercat applauds Monica
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.
为了缩进可变长度的小数。有点笨重,但有效。

