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

前端 未结 8 1672
醉梦人生
醉梦人生 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:31

    In C++11 and later, you can do the following:

    namespace details {
        template
        constexpr size_t max_to_string_length_impl(T value) {
            return (value >= 0 && value < 10) ? 1                            // [0..9] -> 1
                : (std::is_signed::value && value < 0 && value > -10) ? 2 // [-9..-1] -> 2
                : 1 + max_to_string_length_impl(value / 10);                 // ..-10] [10.. -> recursion
        }
    }
    
    template
    constexpr size_t max_to_string_length() { 
        return std::max(
            details::max_to_string_length_impl(std::numeric_limits::max()),
            details::max_to_string_length_impl(std::numeric_limits::min())); 
    }
    

提交回复
热议问题