Correctly pad negative integers with zeros with std::cout

后端 未结 1 999
感动是毒
感动是毒 2021-02-19 11:27

I found this question already asked, but the answer everybody gives is

std::cout << std::setw(5) << std::setfill(\'0\') << value << std::         


        
1条回答
  •  梦如初夏
    2021-02-19 12:08

    std::cout << std::setw(5) << std::setfill('0') << std::internal << -5 << '\n';
    //                                                     ^^^^^^^^
    

    Output:

    -0005
    

    std::internal

    Edit:

    For those those that care about such things, N3337 (~c++11), 22.4.2.2.2:

    The location of any padding is determined according to Table 91.
                      Table 91 - Fill padding
    State                               Location
    adjustfield == ios_base::left       pad after
    adjustfield == ios_base::right      pad before
    adjustfield == internal and a
    sign occurs in the representation   pad after the sign
    adjustfield == internal and
    representation after stage 1 began
    with 0x or 0X                       pad after x or X
    otherwise                           pad before
    

    0 讨论(0)
提交回复
热议问题