enum DayNames {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
int main ()
{
DayNames dayOfWeek;
for (int count=0; count<7; count++)
{
dayOfWeek = count;
if ((dayOfWeek == Saturday) || (dayOfWeek == Sunday))
cout << "Its the weekend - YEAH!!! No school today!" << endl;
else
cout << "...another day of school..." << endl;
}
return 0;
}
I get a compile error saying:
error: invalid conversion from ‘int’ to ‘DayNames’
How do I add one (or go to the next enum value)? Do I have to typecast it to add one or what? This seems like it should be so simple, but isn't working as expected for some reason...
EDIT: Also when I cout dayOfWeek I get the number instead of the name, is there a way to get the name stored in the enum list instead?
No, there is no automatic way of getting the string names as strings so you could cout << "It's " << dayOfWeek.GetName(); //or something like that and get "It's Monday".
Get in the habit of encapsulating reusable code. It will help you develop bigger things faster and cleaner. Here's a version with the day of the week functionality encapsulated. I also renamed the enum to Days because let's face it: It doesn't really provide the names.
#include <iostream>
#include <limits>
using std::cout;
using std::endl;
using std::cin;
//Here's a useful class to stop the console from closing when the program finishes executing.
class PauseConsole
{
public:
~PauseConsole()
{
cout << endl << "Finished. Press ENTER to exit. ";
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
};
enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
class WeekDay
{
private:
//Member data
Days m_id;
//Constructors
public:
WeekDay(Days dayID) : m_id(dayID)
{ }
//Public interface
public:
constchar* GetName()
{
char *name = 0;
switch (m_id)
{
case Sunday: name = "Sunday";
break;
case Monday: name = "Monday";
break;
case Tuesday: name = "Tuesday";
break;
case Wednesday: name = "Wednesday";
break;
case Thursday: name = "Thursday";
break;
case Friday: name = "Friday";
break;
case Saturday: name = "Saturday";
break;
}
return name;
}
bool IsWeekendDay() { return (m_id == Saturday || m_id == Sunday); }
};
int main()
{
PauseConsole __p;
for(int dayID = Sunday; dayID <= Saturday; dayID++)
{
WeekDay day = (Days)dayID;
cout << "It's " << day.GetName() <<
(day.IsWeekendDay() ? " - it's the weekend - YEAH!! No school today!"
: " - another day of school...") << endl;
}
return 0;
}