4

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

Tadeusz A. Kadłubowski
  • 8,047
  • 1
  • 30
  • 37
dave9909
  • 129
  • 1
  • 6

4 Answers4

11

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";
}
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
default
  • 11,485
  • 9
  • 66
  • 102
  • 3
    @johnsyweb: it just came naturally :) – default May 24 '10 at 07:35
  • Curious, why "\n" and not "endl"? – Arun May 24 '10 at 07:57
  • 2
    @ArunSaha `std::endl()` is a function, and its effect is to return a newline character and flush the stream. You may or may not wish to flush the stream. In most cases we don't really care for things at that level and we pick arbitrarily between the two. But if we don't flush, i.e. if we use `'\n'` rather than `std::endl` then things might be somewhat faster. This is because we write to the stream's buffer rather than the output device. By writing to the buffer we delay writing to the output device. Usually IO devices are expensive to write to compared to writing to a buffer in memory. – wilhelmtell May 24 '10 at 08:29
  • So as a guideline, unless you really want something to appear *right now* (for example, while debugging a crash, because delaying could mean it never appears) it's better to let the buffering amortize the cost of writing to the IO device and use `\n`. – Matthieu M. May 24 '10 at 11:52
  • @wilhelmtell: Thanks for the nice explanation. @Mathieu: Thanks for a simple guideline. – Arun May 24 '10 at 15:30
  • Another option is the boost format stuff: See http://stackoverflow.com/questions/119098/which-i-o-library-do-you-use-in-your-c-code/119194#119194 – Martin York May 24 '10 at 17:54
2

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;
}
Alex Korban
  • 14,916
  • 5
  • 44
  • 55
2

Use ios_base::width() and ios::fill():

cout.width(5);
cout.fill('0');
cout << i << endl;

Alternatively, use the IO manipulators:

#include<iomanip>

// ...
cout << setw(5) << setfill('0') << i << endl;
wilhelmtell
  • 57,473
  • 20
  • 96
  • 131
0

Though not required, but if you want to know how to do this with C, here is an example:

for (int i = 0; i <= 9999; i++)
    printf("%04d\n", i);

Here, '0' in "%04d" works like setfill('0') and '4' works like setw(4).

Donotalo
  • 12,748
  • 25
  • 83
  • 121