ANSI-C: maximum number of characters printing a decimal int

前端 未结 8 1670
醉梦人生
醉梦人生 2021-02-19 10:17

I\'d like to know if it is an easy way of determining the maximum number of characters to print a decimal int.

I know contains

8条回答
  •  渐次进展
    2021-02-19 10:46

    After accept answer (2+ yr)

    The following fraction 10/33 exactly meets the needs for unpadded int8_t, int16_t, int32_t and int128_t. Only 1 char extra for int64_t. Exact or 1 over for all integer sizes up to int362_t. Beyond that may be more that 1 over.

    #include 
    #define MAX_CHAR_LEN_DECIMAL_INTEGER(type) (10*sizeof(type)*CHAR_BIT/33 + 2)
    #define MAX_CHAR_SIZE_DECIMAL_INTEGER(type) (10*sizeof(type)*CHAR_BIT/33 + 3)
    
    int get_int( void ) {
                                                //   + 1 for the \n of fgets()
      char draft[MAX_CHAR_SIZE_DECIMAL_INTEGER(long) + 1];  //**
    
      fgets(draft, sizeof draft, stdin);
      return strtol(draft, NULL, 10);
    }
    

    ** fgets() typically works best with an additional char for the terminating '\n'.

    Similar to @R.. but with a better fraction.


    Recommend using generous, 2x, buffers when reading user input. Sometimes a user adds spaces, leading zeros, etc.

      char draft[2*(MAX_CHAR_SIZE_DECIMAL_INTEGER(long) + 1)];
      fgets(draft, sizeof draft, stdin);
    

提交回复
热议问题