c - printf 的参数用作格式说明符的参数

标签 c string-formatting

假设我有以下功能:

void fprint(float f, int ds) {
    printf("%.%df\n", ds, f);
}

我希望调用者指定要打印的 float ,以及小数点后的位数。 (由 .%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);
          ^

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

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

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

最佳答案

您可以在 printf 中使用星号来指定宽度或精度由参数给出——无需创建动态格式字符串。

printf("%.*f", ds, f);

手册页的 printf(3):

Precision

An optional precision, in the form of a period (.) followed by an optional decimal digit string. Instead of a decimal digit string one may write * or *m$ (for some decimal integer m) to specify that the precision is given in the next argument, or in the m-th argument, respectively, which must be of type int. If the precision is given as just ., the precision is taken to be zero. A negative precision is taken as if the precision were omitted. This gives the minimum number of digits to appear for d, i, o, u, x, and X conversions, the number of digits to appear after the radix character for a, A, e, E, f, and F conversions, the maximum number of significant digits for g and G conversions, or the maximum number of characters to be printed from a string for s and S conversions.

关于c - printf 的参数用作格式说明符的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51140390/

相关文章:

c - 如何在输入到文本文件的每个字符串之间添加空格

python - Tkinter 设置输入文本格式

c++ - 将 C 风格的 pretty-print 重构为 C++ 风格的 pretty-print

c++ - 将无符号字符数组转换为整数

c - 我检查字符串内容和长度的程序有一些问题

c - 分段故障Strdup

python - Python 中的字符串格式 : Showing a price without decimal points

c - 将字符串解析为参数,然后连接其中的一些参数

c# - String.Format 格式化没有美分的货币的方法

common-lisp - Common Lisp 中格式指令的安全解析