【问题标题】:What is the difference between conversion specifiers %i and %d in formatted IO functions (*printf / *scanf)格式化 IO 函数 (*printf / *scanf) 中的转换说明符 %i 和 %d 有什么区别
【发布时间】:2010-12-25 23:53:27
【问题描述】:

%d%iprintfscanf 中用作格式说明符时有什么区别?

【问题讨论】:

    标签: c++ c printf scanf format-specifiers


    【解决方案1】:

    它们在用于输出时是相同的,例如printf

    但是,当用作输入说明符时,这些是不同的,例如使用scanf,其中%d 将整数扫描为带符号的十进制数,但%i 默认为十进制,但也允许使用十六进制(如果前面有0x)和八进制(如果前面有0)。

    所以033 将是 27 与 %i 但 33 与 %d

    【讨论】:

    • 在我看来,在 sscanf 中期望一个带有可能零填充的 int 似乎是最合理的默认行为。如果你不期待八进制,那可能会导致微妙的错误。因此,这表明 %d 是一个很好的说明符,可以在您必须任意选择一个时使用,除非您明确想要读取八进制和/或十六进制。
    • 啊!这就说得通了!现在我知道要查找什么,这也可以在 printfscanf 的文档中看到。
    • 八进制的东西在 Javascript 中咬了我一次。 (数据库中的一些数值最初是带有前导零的字符串形式)。那个家伙是个要追查的家伙。
    【解决方案2】:

    这些对于printf 是相同的,但对于scanf 是不同的。对于printf%d%i 都指定有符号十进制整数。对于scanf%d%i 也表示有符号整数,但%i 如果前面有0x 则将输入解释为十六进制数,如果前面有0 则将输入解释为八进制数,否则将输入解释为十进制。

    【讨论】:

      【解决方案3】:

      printf%i%d 格式说明符之间没有区别。我们可以通过转到draft C99 standard 部分7.19.6.1 fprintf 函数 看到这一点,它还涵盖了printf 关于格式说明符,它在第 8 段中说:

      转换说明符及其含义为:

      并包括以下项目符号:

      d,i     The int argument is converted to signed decimal in the style
              [−]dddd. The precision specifies the minimum number of digits to
              appear; if the value being converted can be represented in fewer
              digits, it is expanded with leading zeros. The default precision is
              1. The result of converting a zero value with a precision of zero is
              no characters.
      

      另一方面,scanf 存在差异,%d 假设基数为 10,而 %i 自动检测基数。我们可以通过转到7.19.6.2 部分来看到这一点fscanf 函数 涵盖了scanf 关于格式说明符,在第12 段中它说:

      转换说明符及其含义为:

      并包括以下内容:

      d     Matches an optionally signed decimal integer, whose format is the
            same as expected for the subject sequence of the strtol function with
            the value 10 for the base argument. The corresponding argument shall
            be a pointer to signed integer.
      
      i     Matches an optionally signed integer, whose format is the same as
            expected for the subject sequence of the strtol function with the
            value 0 for the base argument. The corresponding argument shall be a
            pointer to signed integer.
      

      【讨论】:

        【解决方案4】:

        printf 中没有任何内容 - 两者是同义词。

        【讨论】:

        • 正如接受的答案所说,在scanf()格式字符串中使用时会有所不同。
        猜你喜欢
        • 1970-01-01
        • 2020-04-13
        • 2012-06-22
        • 2014-05-30
        • 1970-01-01
        • 2020-12-28
        • 1970-01-01
        • 2012-10-01
        • 2010-10-11
        相关资源
        最近更新 更多