In: Computer Science
Write a c++ program that ask a user to enter his name and birthday (YYYY/MM/DD). If the age is greater than 21 print "welcome," and if the age is less than 21 print "sorry." Use input validation to make sure the birthdate was entered correctly.
#include<iostream>
#include<string>
#include<cstring>
#include <sstream>
#include<cmath>
#include <ctime>
using namespace std;
void date( int a[])
{
time_t t = time(NULL);
tm* timePtr = localtime(&t);
int years;
// extracting current date
int cur_day = timePtr->tm_mday;
int cur_mon = (timePtr->tm_mon)+1;
int cur_year = (timePtr->tm_year)+1900;
if(cur_day < a[2])
{
if (cur_mon == 3)
{
if ((cur_year % 4 == 0 && cur_year % 100 != 0) || (cur_year
% 400 == 0))
{
cur_day += 29;
}
else
{
cur_day += 28;
}
}
else if (cur_mon == 5 || cur_mon == 7 || cur_mon == 10 || cur_mon
== 12)
{
cur_day += 30;
}
else
{
cur_day += 31;
}
cur_mon = cur_mon - 1;
}
if (cur_mon < a[1])
{
cur_mon += 12;
cur_year -= 1;
}
years = cur_year - a[0]; // difference in years of given and
current date
if(years >= 21)
{
cout <<"Welcome";
}
else
{
cout << "Sorry";
}
}
int main()
{
string str, str1 = "";
int a[100];
cout << "Please enter the birthday date: ";
getline (cin, str); // read the current date
int j = 0;
for(int i = 0; i < str.size(); i++ )
{
if(str[i] == '/') // slice the string and convert into int
{
stringstream geek(str1);
int x = 0;
geek >> x;
a[j] = x;
j++;
//cout << x;
str1 = "";
}
else
{
str1 = str1 + str[i];
}
}
stringstream geek(str1);
int x = 0;
geek >> x;
a[j] = x;
j++;
//cout << x;
str1 = "";
if(a[0]>=1900 && a[0]<=9999) // checking for
validation of year
{
//check month
if(a[1]>=1 && a[1]<=12)
{
//check days
if((a[2]>=1 && a[2]<=31) && (a[1]==1 ||
a[1]==3 || a[1]==5 || a[1]==7 || a[1]==8 || a[1]==10 ||
a[1]==12))
date(a);
else if((a[2]>=1 && a[2]<=30) && (a[1]==4 ||
a[1]==6 || a[1]==9 || a[1]==11))
date(a);
else if((a[2]>=1 && a[2]<=28) &&
(a[1]==2))
date(a);
else if(a[2]==29 && a[1]==2 && (a[0]%400==0
||(a[0]%4==0 && a[0]%100!=0)))
date(a);
else
printf("Day is invalid.\n");
}
else
{
printf("Month is not valid.\n");
}
}
else
{
printf("Year is not valid.\n");
}
}
OUTPUT :