Set the number of digits for an Integer

Alex McCoy picture Alex McCoy · Mar 26, 2013 · Viewed 16.6k times · Source

Is there a way in C++ to make the compiler take a certain number of digits even if they first digits are 0's. For example:

I have an item number that is 00001 and when I import the number from the file it displays a 1. I want it to import all five digits and display as 00001.

I don't really have code to display because I don't even know what function to use for this and the code I have is working as advertised, it's just not what I want it to do. I could make the number a string, but I would prefer to keep it an integer.

Answer

LihO picture LihO · Mar 26, 2013

Use std::setfill and std::setw functions:

#include <iostream>
#include <iomanip>

int main()
{
    std::cout << std::setfill('0') << std::setw(5) << 1;
}

outputs:

00001

See related questions:
How can I pad an int with leading zeros when using cout << operator?
Print leading zeros with C++ output operator (printf equivalent)?