Output format question

As a minor part of my program, I am trying to output dates (of the year).

If given: 2/3/2010
I want the format to be: 02/03/10

12/30/1940 ---> 12/30/40
12/3/1845 ----> 12/03/45

etc.

So my question is, how do I print a leading zero onto a number less than 10, and how would I take off the first two digits of a 4 digit number?

I know this would work, but I know there has to be some sort of formatting command for this.
1
2
if(int num < 10)
   cout << "0" << num;


1
2
3
4
5
 
    if (month<10)     cout << 0 << month << "/";
    else cout << month << "/";
    if (day<10) cout << 0 << day << "/";
    else cout << day << "/"; 


See post below
Last edited on
Full code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
using namespace std;

int main()
{
	int month, day;
	string year;

	cout << "Enter month: ";
	cin >> month;
	cout << "Enter day: ";
	cin >> day;
	cout << "Enter year: ";
	cin >> year;
	
	if (month<10)	 cout << 0 << month << "/";
	else cout << month << "/";
	if (day<10) cout << 0 << day << "/";
	else cout << day << "/";
	cout << year[2] << year[3] << endl; // Prints the character in the position 2 & 3, the last two entered. 
	
	return 0;
}


Output test:


Enter month: 2
Enter day: 10
Enter year: 2010
02/10/10
Last edited on
I am not allowed to #include <string> :(
Ah, in that case I'm sorry, no idea :(
Also, I know that I can just print a leading zero by just outputting a zero before the days less than 10, but I was wondering If there is something similar to how setprecision works with setting decimal places. (as i am allowed to #include <iomanip>). But thanks for the help.

For example, what if I wanted everynumber I output to be 10 digits, so if someone gives me a "1" i output "0000000001" (9 zeros). Of if the input is 456, I print 7 leading zeros.
Thanks kempo, I got the leading 0's to be printed using setfill.

But what about cutting off all the digits except for the last 2? Is there a similar command that I can use?
Topic archived. No new replies allowed.