### Invalid Date

Trying to get the program identify an invalid date.

Problems encountered:

Program does not recognize any invalid date.

Program does not recognize when entering February 29th on a year that is not a leap year.

Program does not recognize that February 30, 31, etc is invalid.

 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253`` ``````#include #include using namespace std; int DetermineDayWeek(int, int, int); int dd, mm, yy, a = 0; int main() { do { cout <> mm; cout << "Enter Day : " ; cin >> dd; cout << "Enter Year: " ; cin >> yy; if(yy <= 1912) cout<<"This person is 100 years of age or older"< 0 && mm > 0 && yy > 0); if(dd == 0 && mm == 0 && yy == 0) { DetermineDayWeek(dd, mm, yy); } return 0; } int DetermineDayWeek(int dd, int mm, int yy) { int months[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; if( yy % 4 == 0 ) { months[1] = 29; } for(int i = mm-1; i > 0; i--) { a += months[i-1]; } cout << a + dd << endl; return 0; }``````
First ask 'what is an invalid date' ? Can there be an invalid year ? Invalid month? Day ? Each has to be checked for validity. If any fail then the whole date is invalid right ?

Invalid year: As long as the year is an integer it is essentially valid. So check for that.
Invalid month: There's 12 months in a year - ie: make sure the input is one of those 12 possibilities.
Invalid day: This one is a little more tricky. Any number between 1 and 28 is fine...but days 29, 30, 31 are valid sometimes and other times not. Those exceptions depend on which month it is. So doesn't it make sense to test the validity of the day based on which month it is ?

Leap years: Similar discussion as the invalid day. The leap year effects 1 day. The way to know which year is a leap year u can use the modulus operator since u know that a leap year is every 4 yrs.

All of this should be checked immediately after the user's input.
Last edited on
Hi, this should work :-)

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445`` ``````#include // function prototypes void DetermineDayWeek(int, int, int); int main(void) { int dd,mm,yy = 0; while (true) { std::cout << "Enter Month: "; std::cin >> mm; std::cout << "Enter Day : "; std::cin >> dd; std::cout << "Enter Year: "; std::cin >> yy; if (mm > 0 && dd > 0 && yy > 0) break; } DetermineDayWeek(dd, mm, yy); return 0; } void DetermineDayWeek(int dd, int mm, int yy) { int months[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; if (yy % 4 == 0) months[1] = 29; if (mm <= 12 && dd <= months[mm-1]) { if (yy <= 1912) std::cout<<"This person is 100 years of age or older\n"; std::cout << "Date is valid\n"; } else std::cout << "Err: Date is invalid!!\n"; return; }``````
Topic archived. No new replies allowed.