.

Thursday 22 January 2015

How to validate a date in c++ ?

Validation of date in c++ involves three steps -

1) Declare the function inside the body of a class.

2) Give definition to it outside the class using scope resolution.

3) Call it using do while loop by passing string type of dte in it.

Function Declaration -

class Validate
{
...

bool validateDate(string &);

...
}

Function Definition(Outside the class) -


bool Validate::validateDate(string& str_date)
{
  int d;
char mon1[3];
char mon[4],h1,h2;
int y;
char temp[10];
int m;  
   
   
if (str_date.length() == 9)
{

strcpy(mon1,str_date.substr(3,3).c_str());

d = atoi(str_date.substr(0,2).c_str());
strcpy(mon,str_date.substr(3,3).c_str());

        mon [sizeof(mon ) - 1] = 0;

  y = atoi(str_date.substr(7,2).c_str());

h1 = temp[2];
h2 = temp[6];
mon[0]=tolower(mon[0]);
mon[1]=tolower(mon[1]);
mon[2]=tolower(mon[2]);

if (!strcmp(mon,"jan")){m = 1;}
else if (!strcmp(mon,"feb")) {m=2;}
else if (!strcmp(mon,"mar")) {m=1;}
else if (!strcmp(mon,"apr")) {m=3;}
else if (!strcmp(mon,"may")) {m=1;}
else if (!strcmp(mon,"jun")) {m=3;}
else if (!strcmp(mon,"jul")) {m=1;}
else if (!strcmp(mon,"aug")) {m=1;}
else if (!strcmp(mon,"sep")) {m=3;}
else if (!strcmp(mon,"oct")) {m=1;}
else if (!strcmp(mon,"nov")) {m=3;}
else if (!strcmp(mon,"dec")) {m=1;}
else
{
cout<<endl<<"Invalid Month"<<endl;
return 0;
}

if ( (d>=1 && d<=31)&&(m==1) &&(y>=15 && y<=20))
{
return true;
}
else if((m == 3) && (d>=1 && d<=30) && (y>=15 && y<=20))
{

return true;
}
else if((m == 2) && (d>=1 && d<=28) && (y>=15 && y<=20))
{

return true;
}
else if((m == 2) && (d>=1 && d<=29) && (y==16 || y==20))
{

return true;
}
else
{
cout<<"Invalid Day or Invalid Year"<<endl;
return false;
}
}
else
{
cout<<endl<<"Invalid date format... \n Please Enter in";cout<<" DD-MMM-YY (22-MAR-15)"<<RESET<<endl;
return false;
break;
}
}

Function Calling-

do
{
cout << endl <<CYAN<< "Enter the discount period:"<<RESET;
        getline(cin,d_period);
}while(Validate::validateDate(d_period)!=1);

No comments:

Post a Comment