【问题标题】:scanf crops last byte of numbersscanf 裁剪数字的最后一个字节
【发布时间】:2015-03-08 12:52:12
【问题描述】:

看看这个程序:

#include <stdio.h>

int main()
{
    unsigned i = 0;
    char type = 'a';
    int result = scanf("%u%[asd]", &i, &type);
    printf("result = %d, i = %u\n", result, i);

    return 0;
}

它应该接受一个数字,然后是一个a、s 或d 的字符。当得到第二个数字不匹配的输入时,该数字被正确解析,返回值为1。如果输入的数字后面包含正确的字符,则返回值为2,type被正确解析。但是,该数字的最后一个字节被裁剪(如果我输入小于 256 的任何内容,我得到 0,但如果我输入例如 258 或 510,我仍然得到 256)。为什么是这样?我做错了什么?

【问题讨论】:

    标签: c scanf


    【解决方案1】:

    如果您阅读例如this scanf reference,您会看到"%[" 格式用于读取字符串,其中当然包括写入字符串终止符。

    由于您只提供了一个字符来存储读取的字符串,scanf 函数将总是写出边界并且您有undefined behavior。

    发生的情况是字符串终止符被写入变量i的部分存储空间。

    【讨论】:

      【解决方案2】:
      int result = scanf("%u%[asd]", &i, &type);
      

      说明符"%[...]" 用于扫描字符串。您有兴趣扫描单个字符。

      更改type 或更改说明符。

      #include <stdio.h>
      
      int main()
      {
          unsigned i = 0;
          char type[20] = "a";         // changing type
          int result = scanf("%u%19[asd]", &i, type);
          printf("result = %d, i = %u\n", result, i);
      
          return 0;
      }
      

      #include <stdio.h>
      
      int main()
      {
          unsigned i = 0;
          char type = 'a';
          int result = scanf("%u%c", &i, &type);        // changing specifier
          printf("result = %d, i = %u\n", result, i);
      
          return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-05-30
        • 1970-01-01
        • 2022-10-23
        • 2011-10-12
        • 1970-01-01
        • 2011-04-04
        • 2013-08-26
        相关资源
        最近更新 更多