Set the number of digits for an Integer

16,905

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)?

Share:
16,905
Alex McCoy
Author by

Alex McCoy

Updated on June 20, 2022

Comments

  • Alex McCoy
    Alex McCoy almost 2 years

    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.