Formatting numbers in a loop

I want to list all the numbers from 0000-9999, but I have problems with 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 do this 0001 0002 0003 .... 0010 etc.

+4
source share
4 answers

See setfill for a character fill and setw for a minimum width.

Your case will look like this:

 for(int i = 0; i <= 9999; ++i) { cout << setfill('0') << setw(4) << i << "\n"; } 
+11
source

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; } 
+2
source

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; 
+2
source

Although this is 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) .

0
source

Source: https://habr.com/ru/post/1310712/


All Articles