Aug 24, 2011 at 2:14pm UTC
Well just when you think your done another issue develops lol. I have provided the code that got me this far and it works well but now I have been asked to insert a small fail safe.
I need to test the string (String_To_MDY)to ensure the user enters two digits, followed by a slash, followed by two more digits and a slash, followed by four digits. If not an error message appears and exits the program. Can anyone help?
[code]
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cctype>
using namespace std;
struct DATE_STRUCT
{
int month,
day,
year;
};
void String_To_MDY(char*, DATE_STRUCT&);
bool Validate_Date(DATE_STRUCT&);
char* Strchcpy(char*, char*, int);
int main()
{
char date_string [11];
DATE_STRUCT mdy_date;
char response[2];
cout << endl << endl;
cout << "Do you want to convert and validate a date?(Y/N): ";
cin.getline(response, 2);
while (toupper(*response) == 'Y')
{
cout << endl;
cout << "Enter the date in mm/dd/yyyy form: ";
cin.getline(date_string, 11);
String_To_MDY (date_string, mdy_date);
cout << endl;
cout << "The converted date is the following:" << endl << endl;
cout << "Month:" << setw(4) << mdy_date.month << endl;
cout << "Day: " << setw(4) << mdy_date.day << endl;
cout << "Year: " << setw(4) << mdy_date.year << endl;
if ( Validate_Date(mdy_date) )
{
cout << endl;
cout << "The date is valid.";
}
else
{
cout << endl;
cout << "The date is invalid.";
}
cout << endl << endl;
cout << "Do you want to convert and validate a date?(Y/N): ";
cin.getline(response, 2);
}
cout << endl;
return 0;
} // End of main()
void String_To_MDY(char* date_ptr, DATE_STRUCT& date_struct)
{
char month[3],
day[3],
year[5];
char* ch_ptr;
ch_ptr = date_ptr;
ch_ptr = Strchcpy(month, ch_ptr, '/');
++ch_ptr;
ch_ptr = Strchcpy(day, ch_ptr, '/');
++ch_ptr;
Strchcpy(year, ch_ptr, '\0');
date_struct.month = atoi(month);
date_struct.day = atoi(day);
date_struct.year = atoi(year);
return;
} // End of String_To_MDY()
char* Strchcpy(char* target, char* source, int ch)
{
while (*source != ch && *source != '\0')
{
*target = *source;
++target;
++source;
}
*target = '\0';
return source;
} // End of Strchcpy()
bool Validate_Date(DATE_STRUCT& date_struct)
{
int ny_days [13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int ly_days [13] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (date_struct.month < 1 || date_struct.month > 12)
return false;
if (date_struct.day < 1)
return false;
if (date_struct.year % 4 == 0)
{
if (date_struct.day > ly_days[date_struct.month])
return false;
}
else
if (date_struct.day > ny_days[date_struct.month])
return false;
if (date_struct.year < 1980)
return false;
return true;
} // End of Validate_Date()
[code]