简体   繁体   English

如何在printf()中使用多种精度?

[英]How do I use multiple precisions in printf()?

Looking at the information under the heading " Precision can be omitted or be any of: ". 查看标题为“ 精度可以省略或以下任何一项 ”下的信息。

The example: printf("%.*s", 3, "abcdef"); 示例: printf("%.*s", 3, "abcdef"); works, outputting: abc (truncating the rest of the string.) 起作用,输出: abc (截断字符串的其余部分。)

Now, I would like to have a string with multiple parameters formatted (truncated): 现在,我想将一个带有多个参数的字符串格式化(截断):

printf("%.*s, %.*s", 3, 3, "abcdef", "xyz123");

but the program crashes. 但是程序崩溃了。

What is the correct syntax? 正确的语法是什么?

Thank You. 谢谢。

Maybe you should change order? 也许您应该更改订单?

printf("%.*s, %.*s", 3, "abcdef", 3, "xyz123");

By the way you can hardcode precision if you don't need it as a variable: 顺便说一下,如果您不需要将精度作为变量,则可以对其进行硬编码:

printf("%.3s, %.3s", "abcdef", "xyz123");

(Stephen Canon kindly corrected the typo) (斯蒂芬·佳能请改正错字)

You want to do it like this: 您想要这样做:

printf("%.*s, %.*s", 3, "abcdef", 3, "xyz123");

The format arguments should be in the same order as the format specifiers. 格式参数应与格式说明符顺序相同。

printf("%.*s, %.*s",3,"abcdef",3,"xyz123");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM