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
|
//Do not assing values to the enum members, otherwise the functions will fail
enum Day{Saturday,Sunday, Monday, Tuesday, Wednesday, Thursday, Friday};
std::string daystrtable[7] = { "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" };
std::ostream& operator<<(std::ostream& os, Day d) {
os << daystrtable[static_cast<int>(d)]; //Don't look here. Never cast to or from enums.
return os;
}
std::istream& operator>>(std::istream& is, Day& d) {
std::string str;
is >> str;
std::string *find_str = std::find(daystrtable, daystrtable+7, str);
if (find_str == daystrtable+7) { //No match found
is.setstate(std::ios_base::failbit); //Set failbit
} else {
d = static_cast<Day>(find_str - daystrtable); //Don't look here. Never cast to or from enums.
}
return is;
}
int main() {
Day d = Sunday; //Initalize to silence warnings
std::cout << "Enter a day : ";
if(!(std::cin >> d)) {
std::cout << "\nFailed to read value" << std::endl;
} else {
std::cout << "\nYou've entered " << d << std::endl;
}
}
|