Program to determine valid date.

Feb 17, 2012 at 12:43pm
So I am having a little problem getting this code to work. I feel like I am missing something, but I just can't warp my head around it. any help?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include<iostream>
#include<ctime>
#include<string>

using namespace std;

int main()
{
	#pragma region GetTimeNow
time_t t = time(0);   // get time now
	struct tm * now = localtime( & t );
	int yearNow=(now->tm_year + 1900);
	int monthNow=(now->tm_mon + 1); 
	int daynow=(now->tm_mday);
#pragma endregion GetTimeNow
	
	int date, month, year, numberDays;
	cout << "Please input year: ";
	cin >> year;
	do 
	{
		cout << "Invalid year! Please input year again: ";
		cin >> year;
	} while (year < yearNow);
	cout << "Please input month: ";
	cin >> month;
	do 
	{
		cout << "Invalid month! Please input month again: ";
		cin >> month;
	} while (month>12 && month<0);

	cout << "Please input date: ";
	cin >> date;

	do 
	{
		switch(month)
		{
		case 1:
		case 7:
		case 3:
		case 5:
		case 8:
		case 10:
		case 12:
			numberDays=31;
			break;
		case 2:
			numberDays=28;
			break;
		default:
			numberDays=30;
		}
		cout << "Invalid date! Please input date again: ";
		cin >> date; 

	} while (date > numberDays);
	system("pause");

	return 0;
}
Feb 17, 2012 at 3:35pm
"Doesn't work" is not helpful.

What isn't working?

Compiler error? What's the error and what line is it on?

Unexpected output? What output were you expecting and what are you getting? What input are you giving it?
Last edited on Feb 17, 2012 at 3:36pm
Feb 17, 2012 at 11:17pm
It always asks two times, the first time, it is invalid, the second time it is always correct. For example in the year > yearNow part. I understand that 2012 is assigned to yearNow. I even tried to output yearNow to the screen and found out that it is functioning properly. But when I type in 2012 to year, which is not less than 2012(yearNow), it goes to invalid input and asks for year again. This time when I input 2012, it goes on asking for the month. I'd say that it is a Logical error.
Feb 17, 2012 at 11:37pm
Your asking the user to input twice... no matter what. Change that to a while loop. Do while means "Run this at least once", which is exactly how you have written it.

1
2
3
4
5
6
cin >> year;
do 
{
	cout << "Invalid year! Please input year again: ";
	cin >> year;
} while (year < yearNow);
Topic archived. No new replies allowed.