Hi all:
Is it possible for an int to print a specific number of digits every time?
For example:
int x = 1;
cout <<x <<endl; //should print 001
x = 999;
cout <<x <<endl; //should print 999
Thanks.
Hi all:
Is it possible for an int to print a specific number of digits every time?
For example:
int x = 1;
cout <<x <<endl; //should print 001
x = 999;
cout <<x <<endl; //should print 999
Thanks.
-Zack
You could just add it:
To work with all kinds of numbers:Code:int x = 9; cout << "00" << x << endl;//009
Code:if ( x < 10 ) { cout << "00"; } else if ( x < 100 ) { cout << "0"; } cout << x << endl;
Ah, that works. Good thinking.
I'm going to use that for now. However, I do recall a more elegant way of doing it (by formatting the number before printing, perhaps?). Just for my personal knowledge, does anyone know how this can be done?
Thanks.
-Zack
Code:#include <iostream> #include <iomanip> using namespace std; int main() { for ( int i = 1; i < 1000; i *= 10 ) { cout << setfill('0') << setw(3) << i << '\n'; } } /* my output 001 010 100 */
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
Awesome. Thanks bud.
-Zack