1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
|
// File: mjcdate.cpp
// Operating System: Linux
// Compiler: g++
// Written: 3/2013
// Purpose: This program will take a date as input from the user, and display it in a different format
#include <iostream>
#include <cstring>
struct Date
{
int month;
int day;
int year;
};
//prototypes
void input(struct Date &);
bool validate(const struct Date &);
void output(const struct Date &);
const char *MONTHS[12] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
const int DAYS[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
//initializes variables and calls the other functions
int main()
{
//creating one Date object and a string to contain the user's response when prompted to continue
std::cin >> std::dec;
Date test_date;
int size = 256;
char response_string[size];
//main loop, will terminate when user enters "No"
do
{ //loops until user enters valid date
do
{
test_date.month = test_date.day = test_date.year = 0;
input(test_date);
if(!validate(test_date))
std::cout << "The date you entered is invalid. Please try again" << std::endl;
}while(!validate(test_date));
//outputs the valid date, and prompts user to continue
std::cout << std::endl;
output(test_date);
std::cout << std::endl;
std::cout << "Would you like to continue? Please enter \"Yes\" or \"No\": ";
std::cin.getline(response_string, size);
}while(strcmp(response_string, "No") != 0);
return 0;
}
//takes input from user and puts it in the struct
void input(Date &test_date)
{
std::cout << "Please enter a date in the format M/D/Y or M/D/YYYY: " << std::flush;
std::cin >> test_date.month;
std::cin.ignore(50, '/');
std::cin >> test_date.day;
std::cin.ignore(50, '/');
std::cin >> test_date.year;
std::cin.clear(); //will clear any remaining garbage in the buffer
std::cin.ignore(50, '\n' );
}
//validates struct entered by user is a valid date
bool validate(const Date &test_date)
{
bool flag = false;
if(test_date.month >= 1 && test_date.month <= 12)
if(test_date.day >= 1 && test_date.day <= DAYS[test_date.month-1])
if(test_date.year >= 0 && test_date.year <= 99)
flag = true;
else if(test_date.year >= 1000 && test_date.year <= 9999)
flag = true;
return flag;
}
//outputs date structure in Month, Day Year format i.e. March 8, 2013
void output(const Date &test_date)
{
std::cout << "The date you entered is: " << MONTHS[test_date.month-1] << " " << test_date.day << ", ";
if(test_date.year < 100)
std::cout << test_date.year + 2000;
else
std::cout << test_date.year;
std::cout << std::endl;
}
|