Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting numbers in loop

I want to list all numbers from 0000-9999 however I am having trouble holding the zero places.

I tried:

for(int i = 0; i <= 9999; ++i)
{
cout << i << "\n";
}

but I get: 1,2,3,4..ect How can I make it 0001,0002,0003....0010, etc

like image 203
dave9909 Avatar asked Dec 08 '22 03:12

dave9909


2 Answers

See setfill for specifying the fill character, and setw for specifying the minimum width.

Your case would look like:

for(int i = 0; i <= 9999; ++i)
{
    cout << setfill('0') << setw(4) << i << "\n";
}
like image 65
default Avatar answered Dec 27 '22 21:12

default


You just need to set some flags:

#include <iostream>
#include <iomanip>

using namespace std;
int main()
{
    cout << setfill('0');
    for(int i = 999; i >= 0; --i)
    {
        cout << setw(4) << i << "\n";
    }
    return 0;
}
like image 29
Alex Korban Avatar answered Dec 27 '22 22:12

Alex Korban