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 <= 9开发者_开发问答999; ++i)
{
cout << i << "\n";
}
but I get: 1,2,3,4..ect How can I make it 0001,0002,0003....0010, etc
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";
}
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;
}
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;
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)
.
精彩评论