How can I pad an int with leading zeros when using cout << operator?


I want cout to output an int with leading zeros, so the value 1 would be printed as 001 and the value 25 printed as 025. How can I do this?

4/5/2018 2:41:59 AM

With the following,

#include <iomanip>
#include <iostream>

int main()
    std::cout << std::setfill('0') << std::setw(5) << 25;

the output will be


setfill is set to the space character (' ') by default. setw sets the width of the field to be printed, and that's it.

If you are interested in knowing how the to format output streams in general, I wrote an answer for another question, hope it is useful: Formatting C++ Console Output.

7/26/2019 6:26:58 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow