fork download
  1. #include <iostream>
  2. #include <ctime>
  3.  
  4. using namespace std;
  5.  
  6. int calculateAge(int birthYear, int birthMonth, int birthDay) {
  7. // Get current date
  8. time_t t = time(nullptr);
  9. tm* now = localtime(&t);
  10.  
  11. int currentYear = now->tm_year + 1900;
  12. int currentMonth = now->tm_mon + 1;
  13. int currentDay = now->tm_mday;
  14.  
  15. // Calculate age
  16. int age = currentYear - birthYear;
  17.  
  18. // Adjust for whether birthday has occurred this year
  19. if (currentMonth < birthMonth || (currentMonth == birthMonth && currentDay < birthDay)) {
  20. age--;
  21. }
  22.  
  23. return age;
  24. }
  25.  
  26. int main() {
  27. int birthYear, birthMonth, birthDay;
  28.  
  29. cout << "Enter your birth year: ";
  30. cin >> birthYear;
  31. cout << "Enter your birth month (1-12): ";
  32. cin >> birthMonth;
  33. cout << "Enter your birth day: ";
  34. cin >> birthDay;
  35.  
  36. int age = calculateAge(birthYear, birthMonth, birthDay);
  37.  
  38. cout << "Your age is: " << age << " years old." << endl;
  39.  
  40. return 0;
  41. }
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
Enter your birth year: Enter your birth month (1-12): Enter your birth day: Your age is: -19972 years old.