c++formattingnumbers

Print leading zeros with C++ output operator?


How can I format my output in C++? In other words, what is the C++ equivalent to the use of printf like this:

printf("%05d", zipCode);

I know I could just use printf in C++, but I would prefer the output operator <<.

Would you just use the following?

std::cout << "ZIP code: " << sprintf("%05d", zipCode) << std::endl;

Solution

  • This will do the trick, at least for non-negative numbers(a) such as the ZIP codes(b) mentioned in your question.

    #include <iostream>
    #include <iomanip>
    
    using namespace std;
    cout << setw(5) << setfill('0') << zipCode << endl;
    
    // or use this if you don't like 'using namespace std;'
    std::cout << std::setw(5) << std::setfill('0') << zipCode << std::endl;
    

    The most common IO manipulators that control padding are:

    Note that these function affect the global state of the cout object. That means that doing this in one place will have unintended effects in later usages of std::cout, if you don't undo the manipulations!

    And just on your preference for using <<, I'd strongly suggest you look into the fmt library (see https://github.com/fmtlib/fmt). This has been a great addition to our toolkit for formatting stuff and is much nicer than massively length stream pipelines, allowing you to do things like:

    cout << fmt::format("{:05d}", zipCode);
    

    The fmt::format functionality is included in C++20 as std::format.
    C++23 brings std::print, which allows you to do std::print("{:05d}", zipCode); directly (with no need to go through cout).


    (a) If you do need to handle negative numbers, you can use std::internal as follows:

    cout << internal << setw(5) << setfill('0') << zipCode << endl;
    

    This places the fill character between the sign and the magnitude.


    (b) This ("all ZIP codes are non-negative") is an assumption on my part but a reasonably safe one, I'd warrant :-)