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
|
#include <iostream>
#include <string> // *** EDIT: added
enum { Jan = 1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec };
static_assert( Dec == Jan + 11, "wrong number of months" ) ;
constexpr int calendar_start = 1583 ; // first full year of the gregorian calendar
// invariant: year > calendar_start
bool is_leap( int year )
{
if( year%400 == 0 ) return true ;
else return year%4 == 0 && year%100 != 0 ;
}
// invariant: month in [Jan,Dec], year > calendar_start
int num_days_in_month( int month /* Jan == 1 */, int year )
{
static const int ndays[] = { 0 /* not used */, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } ;
static_assert( sizeof(ndays) / sizeof( ndays[0] ) == Jan + 12, "wrong array size" ) ;
if( month == Feb && is_leap(year) ) return 29 ;
else return ndays[month] ;
}
// read in an integer in the range [minv,maxv]
int get_int( std::string prompt, int minv, int maxv )
{
std::cout << prompt << " [" << minv << ',' << maxv << "]: " ;
int value ;
if( std::cin >> value )
{
if( value >= minv && value <= maxv ) return value ;
else std::cout << "the value is out of range. " ;
}
else // non-numeric input
{
std::cout << "non-numeric input. " ;
std::cin.clear() ; // clear the failed state
std::cin.ignore( 1000000, '\n' ) ; // throw the bad input away
}
std::cout << "try again.\n" ;
return get_int( prompt, minv, maxv ) ; // try again
}
int get_month() { return get_int( "month", Jan, Dec ) ; }
int get_year() { return get_int( "year", calendar_start, 999999 ) ; }
int main()
{
const int month = get_month() ;
const int year = get_year() ;
std::cout << "days in the month: " << num_days_in_month( month, year ) << '\n' ;
}
|