Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@plusangel
Created May 3, 2020 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plusangel/34d1c0d647b1154bc6a84d0735bdf5f8 to your computer and use it in GitHub Desktop.
Save plusangel/34d1c0d647b1154bc6a84d0735bdf5f8 to your computer and use it in GitHub Desktop.
//
// Tell me about your birthday!
// Created by angelos on 03/05/2020.
//
#include <ctime>
#include <iostream>
#include <string_view>
int validate_input(int lower_limit, int upper_limit, std::string_view prompt);
void year(tm &birthday);
void month(tm &birthday);
void day(tm &birthday);
bool isLeapYear(int year);
void display(const tm &birthday);
int main() {
tm birthday{};
std::cout << "Please submit your date of birth." << std::endl;
year(birthday);
month(birthday);
day(birthday);
display(birthday);
return 0;
}
void year(tm &birthday) {
birthday.tm_year = validate_input(1950, 2020, "What is the year? ");
}
void month(tm &birthday) {
birthday.tm_mon = validate_input(1, 12, "What is the month? ");
}
void day(tm &birthday) {
int upper_limit;
if (birthday.tm_mon == 2) {
if (isLeapYear(birthday.tm_year))
upper_limit = 29;
else
upper_limit = 28;
} else if (birthday.tm_mon == 1 || birthday.tm_mon == 3 || birthday.tm_mon == 5 || birthday.tm_mon == 7 || birthday.tm_mon == 8 || birthday.tm_mon == 10 || birthday.tm_mon == 12)
upper_limit = 31;
else
upper_limit = 30;
birthday.tm_mday = validate_input(1, upper_limit, "What is the day? ");
}
int validate_input(const int lower_limit, const int upper_limit, std::string_view prompt) {
int input{};
bool repeat{false};
do {
std::cout << prompt;
std::cin >> input;
if (input < lower_limit || input > upper_limit) {
repeat = true;
std::cout << "Invalid input, please try again!" << std::endl;
} else {
repeat = false;
}
} while (repeat);
return input;
}
bool isLeapYear(const int year) {
if (year % 4 == 0) {
if (year % 100 == 0) {
// the year is a leap year if it is divisible by 400.
if (year % 400 == 0)
return true;
else
return false;
} else
return true;
} else
return false;
}
void display(const tm &birthday) {
const std::string month_names[12] = {
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};
std::cout << "Your birthday is on: " << std::endl;
std::cout << month_names[birthday.tm_mon - 1] << " " << birthday.tm_mday << ", " << birthday.tm_year << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment