4

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.

Alex McCoy
  • 91
  • 1
  • 2
  • 4

3 Answers3

11

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

Community
  • 1
  • 1
LihO
  • 41,190
  • 11
  • 99
  • 167
0

Things like item numbers are typically used as identifiers; the fact that they look like numbers is a distraction. Store them as strings.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
-1

Basically, no. The native data types do not contain any formatting information. You need to keep track of the formatting yourself. You only need the formatting when you need to output the number.

One way of making it easier is to create a class for formatted numbers where you combine a number with a format.

Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82