Using scanf for reading an unsigned char

前端 未结 2 2000
刺人心
刺人心 2020-12-31 00:17

I\'m trying to use this code to read values between 0 to 255 (unsigned char).

#include
int main(void)
{
    unsigned char value;         


        
相关标签:
2条回答
  • 2020-12-31 00:45

    The %u specifier expects an integer which would cause undefined behavior when reading that into a unsigned char. You will need to use the unsigned char specifier %hhu.

    0 讨论(0)
  • 2020-12-31 01:06

    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.

    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(

    Hope this is not off topic as I still used scanf and not another function like getchar :)

    Another approach (without extra function)

    if (scanf("%u", &uiTemp) == 1 && uiTemp < 256) { value = uitemp; }
    else {/* Do something for conversion error */}
    
    0 讨论(0)
提交回复
热议问题