【问题标题】:Using scanf for reading an unsigned char使用 scanf 读取无符号字符
【发布时间】:2012-12-18 06:13:41
【问题描述】:

我正在尝试使用此代码读取 0 到 255 (unsigned char) 之间的值。

#include<stdio.h>
int main(void)
{
    unsigned char value;

    /* To read the numbers between 0 to 255 */
    printf("Please enter a number between 0 and 255 \n");
    scanf("%u",&value);
    printf("The value is %u \n",value);

    return 0;
}

我确实按预期收到了以下编译器警告。

警告:格式“%u”需要类型“unsigned int *”,但参数 2 的类型为“unsigned char *”

这是我对这个程序的输出。

请输入 0 到 255 之间的数字 45 值为 45 分段故障

我在运行此代码时确实遇到了分段错误。

使用scanf 读取unsigned char 值的最佳方法是什么?

【问题讨论】:

  • 其实%hhuunsigned char
  • @TJD。我不想读一个字符。我想读取 0 到 255 之间的值。
  • @乔。那效果很好。非常感谢。
  • user1293997:您可能想写一个答案并接受它(假设@Joe 对此不感兴趣)。目前唯一的答案是完全不正确的。

标签: c scanf


【解决方案1】:

%u 说明符需要一个整数,当将其读入unsigned char 时会导致未定义的行为。您将需要使用 unsigned char 说明符 %hhu

【讨论】:

  • 这真的很好 - 但是 gcc 在 C89/C90 模式下抱怨很可悲 - 而且 ms 还抱怨:据我所知,%hhu 不支持早于 C99。
  • @BastianEbeling yes here hh 被标记为黄色,这意味着它是从 C99 开始引入的。我想知道如何在 C89 中阅读它
  • 下面有一个使用getchar()的例子现在被删除了。
  • 为什么那个 getchar() 例子被删除了,跑题了?
【解决方案2】:

对于 C99 之前的版本,我会考虑为此编写一个额外的函数 只是为了避免由于 scanf 的未定义行为而导致的分段错误。

方法:

#include<stdio.h>
int my_scanf_to_uchar(unsigned char *puchar)
{
  int retval;
  unsigned int uiTemp;
  retval = scanf("%u", &uiTemp);
  if (retval == 1)   
  {
    if (uiTemp < 256) {
      *puchar = uiTemp;
    }
    else {
      retval = 0; //maybe better something like EINVAL
    }
  }
  return retval; 
}

然后将scanf("%u",替换为my_scanf_to_uchar(

希望这不是题外话,因为我仍然使用 scanf 而不是像 getchar 这样的其他功能 :)

另一种方法(没有额外功能)

if (scanf("%u", &uiTemp) == 1 && uiTemp < 256) { value = uitemp; }
else {/* Do something for conversion error */}

【讨论】:

    猜你喜欢
    • 2013-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    相关资源
    最近更新 更多