Correctly pad negative integers with zeros with std::cout
Asked Answered
O

2

14

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

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

which is fine for positive numbers, but with -5, it prints:

000-5

Is there a way to make it print -0005 or to force cout to always print at least 5 digits (which would result in -00005) as we can do with printf?

Ontine answered 9/7, 2013 at 8:51 Comment(0)
V
19
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
Voluptuous answered 9/7, 2013 at 8:54 Comment(1)
You're very welcome! This question went nice and quickly. Hope this helps other people too.Voluptuous
A
3

In C++20 you'll be able to use std::format to do this:

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

Output:

-0005

In the meantime you can use the {fmt} library, std::format is based on. {fmt} also provides the print function that makes this even easier and more efficient (godbolt):

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

Disclaimer: I'm the author of {fmt} and C++20 std::format.

Aeon answered 3/3, 2021 at 4:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.