Printing one digit integers with two digits

Jul 29, 2009 at 6:35pm
Hi there,

I am trying to write a program in which I need to get printed some integer numbers. This is an easy task, but one point is I need integers less than 10 to be printed with an extra zero preceding the number, for example, to print 08 when the number is 8.

Could you please help me on this?
Thanks,

MarioAAO.
Jul 29, 2009 at 6:47pm
Could you not just use something like if(num<10)cout << "0" << num;
Jul 29, 2009 at 6:48pm
Something like this?
When you print the number it must be outside the if statement or it will only print when it is below 10.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
     int Number = 0;

     cout << "Enter your number: ";
     cin >> Number;
     if (Number < 10){
           cout << "0";
          }
     cout << Number << endl;
     system("PAUSE");
     return 0;
}
Last edited on Jul 29, 2009 at 6:50pm
Jul 29, 2009 at 7:12pm
1
2
3
4
5
#include <iostream>
#include <iomanip>

int i(7), j(10);
std::cout << std::setw(2) << std::setfill('0') << i << ", " << j << std::endl;


Learn to use the iomanipulators with streams. It is much better than writing your own loops. FYI
http://cplusplus.com/reference/iostream/manipulators/
Jul 29, 2009 at 9:33pm
Aye aye captain!
Topic archived. No new replies allowed.