【问题标题】:Correctly pad negative integers with zeros with std::cout用 std::cout 正确地用零填充负整数
【发布时间】:2013-07-06 19:16:51
【问题描述】:

我发现这个问题已经问过了,但大家给出的答案是

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

这对于正数来说很好,但对于 -5,它会打印:

000-5

有没有办法让它打印 -0005 或强制 cout 总是打印至少 5 位数字(这将导致 -00005),就像我们可以使用 printf 一样?

【问题讨论】:

    标签: c++ iostream cout iomanip


    【解决方案1】:
    std::cout << std::setw(5) << std::setfill('0') << std::internal << -5 << '\n';
    //                                                     ^^^^^^^^
    

    输出:

    -0005
    

    std::internal

    编辑:

    对于那些关心这些事情的人,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
    

    【讨论】:

    • 不客气!这个问题很好,很快。希望这对其他人也有帮助。
    【解决方案2】:

    在 C++20 中,您将能够使用 std::format 来执行此操作:

    std::cout << std::format("{:05}\n", -5);  
    

    输出:

    -0005
    

    同时你可以使用the {fmt} librarystd::format是基于。 {fmt} 还提供了print 函数,使这更容易和更高效(godbolt):

    fmt::print("{:05}\n", -5); 
    

    免责声明:我是 {fmt} 和 C++20 std::format 的作者。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-20
      • 2019-03-15
      • 1970-01-01
      • 2014-10-05
      • 2020-06-06
      • 1970-01-01
      • 2011-09-17
      • 2010-10-03
      相关资源
      最近更新 更多