Width for any value of an unsigned (natural) number

Background

I have a registration system that displays entries on std::ostream. Each record is annotated by a counter, which is incremented by one with each output, for example:

=====  Batch # 5  =====
  This is the fifth record
=====  Batch # 19  =====
  This is the nineteenth record
=====  Batch # 187  =====
  Who knows to spell *that*?

Counter std::size_ti.e. unsigned integer.

Problem

As now, the numbers are displayed without any additions, which looks ugly. I would like to achieve this:

=====  Batch #     5  =====
  This is the fifth record
=====  Batch #    19  =====
  ...
=====  Batch #   187  =====
=====  Batch # 12345  =====

Creating a handle to a stream object can be achieved with std::setw. However, I still need to know how many digits the base-10 representation takes as much as possible.

Inquiry

(.. ), base-10 a std::size_t. , , , ++ 14 () constexpr s.

,

, N -B , ( B- N) 1. , 100 10, 100 1 3; 1234 10, ( 1234) 1 4. --:

digits( value , base ) = floor( logarithm( radicand=value , index=base ) ) + 1

; - , , . . , , .

std::size_t, std::numeric_limits<std::size_t>::max().


. , , , -.

+4
2

++ std::numeric_limits, . - 10 , , digits10, constexpr int. , , 1. :

template<class T>
constexpr int maximum_base10_digits =
    std::numeric_limits<T>::digits10 + 1;

, ( , , std::setw, ... !).

cppreference.com - std::size_t, , std::numeric_limits, :

, ( std::size_t std::streamsize) std::numeric_limits.

, ++ 11 ( ++ 98, constexpr), ++. , ++ 14.

#include <cstddef>
#include <iomanip>
#include <iostream>
#include <limits>


namespace
{
    template<typename T>
    void
    pretty_print
    (
     const T value
    )
    {
        // Ensure that it computed at compile-time
        constexpr int maximum_digits = std::numeric_limits<T>::digits10 + 1;

        std::cout << std::setw( maximum_digits ) << value << '\n';
    }
}

int
main
( )
{
    pretty_print( std::size_t{ 7 } );
    pretty_print( std::numeric_limits<std::size_t>::max() );
}

++ 11 std::numeric_limits::max_digits10 (. ). , , , 0 .

+1
+7

All Articles