Can someone help me with my code? It converts numbers up to 365 into month day format. The problem is when I enter 0 it converts it into January 0 and the program ends. I do not want the program to convert 0 to January 0. Need help.
#include <iostream> #include <string> using namespace std; //Day of the year class declaration class DayOfYear { private: public: void print(int); }; static const int MonthDays[] = {31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}; //Set the name of each month into an array static const string MonthName[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; //************************************************** // This function displays the month and day using * // the number entered. * //************************************************** void DayOfYear::print(int day) { int month = 0; while (MonthDays[month] < day) month = (month + 1) %12; //Display month and day cout << MonthName[month] << " "; if(month == 0) cout<<day; else cout<< day - MonthDays[month-1]; } int main() { DayOfYear dYear; //Set days of each month into an array int day; //Ask user the total day number do {cout << "\nEnter a number you would like to convert into a month and day"; cin >> day; //Send entered day number to the print() function dYear.print(day); }while( day != 0); return 0; }
Well, you are using a do while, so you need to either change that or you need a sanity check elsewhere.
In fact, you really should do some input checking for values outside your allowed input. Then send an error or exit at that point.
{cout << "\nEnter a number between 1 and 365 you would like to convert into a month and day, 0 to exit."; cin >> day; if (day <= 0 || day > 365) continue;
And that also works nicely with a while rather than a do while. I don't remmber off and if continue checks the while or if it skips back to the do. If it goes to the do, use a while and just iniialize day to somethig other than 0. Then the first user input wil overwrite that and any time they hit 0 or outside the domain you have told them, it just exits or asks again.
Ok, Thank you very much, you made me remember. I fixed with the this if(day = 0) exit(0); else
Join our real-time social learning platform and learn together with your friends!