views:

117

answers:

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

+10  A: 

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";
}
Default
+1 for correcting indentation while answering question.
Johnsyweb
@johnsyweb: it just came naturally :)
Default
Curious, why "\n" and not "endl"?
ArunSaha
@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
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.
@wilhelmtell: Thanks for the nice explanation. @Mathieu: Thanks for a simple guideline.
ArunSaha
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
+2  A: 

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 - Aotea Studios
+2  A: 

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
Is the top way able to do it without the extra header file?
dave9909
@dave9909 Yes .
wilhelmtell
A: 

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