【问题标题】:Using constant defined number of digits使用常量定义的位数
【发布时间】:2014-06-09 13:35:52
【问题描述】:

我想使用一个常量定义的位数

    #define DIGITS 10
    printf(%0DIGITSd \n, myvalue)

这行得通吗?如果没有,我怎样才能以简单的方式做到这一点?

【问题讨论】:

  • 要获得更好的答案,请定义如果myvalue 的位数少于DIGITS(零填充、空格填充、左侧或右侧)时该怎么做。如果myvalue 的位数多于DIGITS,则定义所需的内容。 (无论如何打印更宽,左截断,右截断,****)

标签: c constants c-preprocessor digits


【解决方案1】:

字符串周围缺少引号。

在 C 中,字符串实际上是由字符串字面量的序列 指定的。所以你可以这样做:

#define DIGITS "10"

printf( "%0" DIGITS "d\n", myvalue );

预处理器还可以从其他标记(例如数字)生成字符串。检查 stringize 运算符 (#),但我建议仅在您确实需要时使用它。

【讨论】:

  • 完美!非常感谢 ! Ps:省略的引号是故意的。我不知道该怎么做^^
【解决方案2】:

您可以将宽度作为参数传递给printf

 printf("%0*d \n", DIGITS, myvalue)

【讨论】:

  • [Edit1] 感谢您的回答!那么 sscanf 呢?假设我想这样做: sscanf(buff.data,"%06\n",&value);具有恒定定义的位数。如何将宽度传递给 sscanf ?
  • @user3290274 似乎sscanf* 用于不同的目的。唯一的方法是使用字符串文字技巧,如 Potatoswatter 的回答。
【解决方案3】:

不,它不会这样工作,宏名称不会插入到字符串文字中。

我认为不可能在 C 中执行此操作,除非您执行 #define DIGITS "10" 或生成(部分)源文件。或者,如果 DIGITS 是 0 到 10 之间的十进制常量,请尝试这个技巧:

#define DIGITS 10
#define STR_0 "0"
#define STR_1 "1"
#define STR_2 "2"
#define STR_3 "3"
#define STR_4 "4"
#define STR_5 "5"
#define STR_6 "6"
#define STR_7 "7"
#define STR_8 "8"
#define STR_9 "9"
#define STR_10 "10"
#define STR(i) STR_##i

...
  printf("%0" STR(DIGITS) "d\n", myvalue);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-20
    • 2016-11-13
    • 2014-08-27
    • 2018-12-28
    • 2016-08-19
    • 2020-08-22
    相关资源
    最近更新 更多