简体   繁体   English

使用scanf读取unsigned char

[英]Using scanf for reading an unsigned char

I'm trying to use this code to read values between 0 to 255 ( unsigned char ). 我正在尝试使用此代码读取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;
}

I do get the following compiler warning as expected. 我按预期得到了以下编译器警告。

warning: format ‘%u’ expects type ‘unsigned int *’, but argument 2 has type ‘unsigned char *’

And this is my output for this program. 这是我对该计划的输出。

Please enter a number between 0 and 255
45
The value is 45 
Segmentation fault

I do get the segmentation fault while running this code. 运行此代码时,我确实遇到了分段错误。

What is the best way to read unsigned char values using scanf ? 使用scanf读取unsigned char值的最佳方法是什么?

The %u specifier expects an integer which would cause undefined behavior when reading that into a unsigned char . %u说明符需要一个整数,当将其读入unsigned char时会导致未定义的行为。 You will need to use the unsigned char specifier %hhu . 您将需要使用unsigned char说明符%hhu

For pre C99 I would consider writing an extra function for this just alone to avoid that segmentation fault due to undefined behaviour of scanf. 对于C99之前,我会考虑单独为此编写一个额外的函数,以避免由于scanf的未定义行为导致的分段错误。

Approach: 做法:

#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; 
}

Then replace scanf("%u", with my_scanf_to_uchar( 然后用my_scanf_to_uchar(替换scanf("%u",

Hope this is not off topic as I still used scanf and not another function like getchar :) 希望这不是主题,因为我仍然使用scanf而不是像getchar这样的另一个函数:)

Another approach (without extra function) 另一种方法(没有额外的功能)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM