Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the number of digits for an Integer [duplicate]

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.

like image 540
Alex McCoy Avatar asked Dec 27 '22 06:12

Alex McCoy


1 Answers

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

like image 129
LihO Avatar answered Dec 28 '22 20:12

LihO