printf的参数,用作格式说明符的参数

boo*_*max 0 c string-formatting

假设我有以下功能:

void fprint(float f, int ds) {
    printf("%.%df\n", ds, f);
}
Run Code Online (Sandbox Code Playgroud)

我希望调用者指定要打印的浮点数,以及小数点后的位数.(由说明者.%d指示)

但是,在编译时我得到2个警告:

./sprint.h: In function ‘fprint’:
./sprint.h:19:14: warning: conversion lacks type at end of format [-Wformat=]
     printf("%.%df\n", ds, f);
          ^
Run Code Online (Sandbox Code Playgroud)

./sprint.h:19:12: warning: too many arguments for format [-Wformat-extra-args]
     printf("%.%df\n", ds, f);
            ^~~~~~~~~
Run Code Online (Sandbox Code Playgroud)

在调用它时:fprint(3.1422223f, 3);它产生输出:%df.我也尝试在函数声明中交换参数的顺序,但它会产生相同的警告.

我的问题是:如何将格式说明符(例如%d在本例中)注入现有格式说明符?

Ry-*_*Ry- 6

您可以使用星号printf来指定参数给出的宽度或精度 - 无需创建动态格式字符串.

printf("%.*f", ds, f);
Run Code Online (Sandbox Code Playgroud)

man-pages的printf(3):

精确

一个可选的精度,以句点(.)后跟可选的十进制数字字符串的形式. 可以写入**m$(对于某些十进​​制整数m)而不是十进制数字串来指定精度在下一个参数或第m个参数中给出,它们必须是int类型. 如果精度是公正的.,则精度为零.如果省略精度,则采用负精度.这给出的最小位数出现了d,i,o,u,x,和X转换,为基数字符后出现的位数a,A,e,E,f,和F转换的显著位数的最大数目gG转换,或最大要从字符串sS转换打印的字符数.