+ 1

How can i create an IF statement to fix limitations in age calculator in C++?

I successfully created a working birthday calculator in C++. However, I am trying to add limitations such as dates like feb. 31 is seen as an error. Can you help suggest best of defining or going about adding this to the program? for example, if I entered June 31, 1996, I would like the program to identify it as an error rather than calculating the age as june does not have a 31st day. code below: int main() { int age; int currentyear=2018, currentmonth=05, currentday=25; int birthyear, birthmonth, birthday; cout <<"Enter your birth year: "; cin >> birthyear; cout <<"Enter your birth month in the format MM: "; cin >> birthmonth; cout <<"Enter birth day in the format DD: "; cin >> birthday; age = ((currentyear*10000 + currentmonth*100 + currentday) - (birthyear*10000 + birthmonth*100 + birthday) )/10000 ; if (birthyear >= 2017 && birthmonth > 05 && birthday >25) cout << "This person has not been born yet or is not a year old"; else cout << "You are " << age << " years old as of May 25, 2018!" <<endl; }

25th May 2018, 4:03 PM
shamizzle
2 Réponses
+ 4
You can use an array and fill it up with maximum number of days in each month. Later on, you can compare the user input, whether or not it is between 1 and the number in the array. If the number supplied by user is out of range warn user. Additionally, for the month of February you can implement leap year check because number of days in February differs in leap years. Hth, cmiiw
25th May 2018, 6:37 PM
Ipang
+ 1
if(birthmonth == 2 && birthday >28) cout << "Date does not exists"; //use the same logic for 30 and 31 days
25th May 2018, 4:18 PM
‎ ‏‏‎Anonymous Guy