c++ - Parameter issue? at least i think it is -
#include <iostream> #include <stdio.h> #include <iomanip> using namespace std; class date { private: int year; int monthnum; int daynum; public: date(int newyear = 1900, int newmonth = 1, int newday = 1); void setdate(int changeyear, int changemonth, int changeday); void displaynumerically(); void displaytextually(); }; int main() {
how make when setdate called , parameters incorrect returns date trying change
date f(1980, 6, 8); f.displaynumerically(); /// prints "06/08/1980" f.displaytextually(); /// prints "june 8, 1980" f.setdate(1980, 6, 31); /// prints "error: setdate() called invalid date information" f.displaynumerically(); /// prints "06/08/1980" f.displaytextually(); /// prints "june 8, 1980"*
this section right above.
return 0; } date::date(int newyear, int newmonth, int newday) { year = newyear; monthnum = newmonth; daynum = newday; if(newday > 30) { cout <<"error: date created invalid date information."<<endl; year = 1900; monthnum = 1; daynum = 1; } } void date::setdate(int changeyear, int changemonth, int changeday) { year = changeyear; monthnum = changemonth; daynum = changeday; if(changemonth > 12||changeday > 30) { cout <<"error: setdate() called invalid date information."<<endl; year=1; monthnum=1; daynum=1; } } void date::displaynumerically() { printf("%02d",monthnum); printf("/%02d",daynum); printf("/%04d\n",year); } void date::displaytextually() { string m; if( monthnum == 1) m = "january"; else if( monthnum == 2) m = "february"; else if( monthnum == 3) m = "march"; else if( monthnum == 4) m = "april"; else if( monthnum == 5) m = "may"; else if( monthnum == 6) m = "june"; else if( monthnum == 7) m = "july"; else if( monthnum == 8) m = "august"; else if( monthnum == 9) m = "september"; else if( monthnum == 10) m = "october"; else if( monthnum == 11) m = "november"; else if( monthnum == 12) m = "december"; else cout <<"invalid month input: "<< monthnum << endl; cout << m <<" "<<fixed<<setprecision(2)<<daynum<<","<<year<<endl; }
just don't modify date when input faulty:
void date::setdate(int changeyear, int changemonth, int changeday) { if(changemonth > 12||changeday > 30) { cout <<"error: setdate() called invalid date information."<<endl; } else { year = changeyear; monthnum = changemonth; daynum = changeday; } }
(i'm assuming validity check illustration purposes.)
Comments
Post a Comment