Switches are used for checking against integral constants so you can actually switch on the enumerated values you have, such as with:
switch (day) {
case Mon: case Tue: case Wed: case Thu: case Fri:
cout << "Weekday"; break;
case Sun: case Sat:
cout << "Weekend"; break;
default:
cout << "??"; break;
}
cout << '\n';
However, you can't enter the enumerated values in the way you expect, entering the word Tue
and having that magically converted to the value 2
. If you have the following code:
int x = 42;
std::cin >> x;
and you enter a non-numeric like Tue
, x
will not be any useful value that you can use. That's almost certainly the reason why, as you mention in a comment, it tells you it's the weekend no matter which textual day you enter. There's a good chance they all set x
to zero (Sunday) because they cannot be immediately interpreted as an integer.
What you can do to allow textual input is to provide a function which does that conversion work for you, something like the one shown in this complete program:
#include <iostream>
#include <string>
#include <algorithm>
int getDayOfWeek(std::string textDay) {
// Only use up to three characters, and lower-case.
std::string day = textDay.substr(0,3);
std::transform(day.begin(), day.end(), day.begin(), ::tolower);
// Search through collection until found then return index.
int dayOfWeek = 0;
for (std::string chk: {"sun", "mon", "tue", "wed", "thu", "fri", "sat"}) {
if (day == chk) return dayOfWeek;
++dayOfWeek;
}
// Not found, return sentinel value.
return -1;
}
// Test harness to allow you to enter arbitrary lines and
// convert them to day indexes. Hit ENTER on its own to stop.
int main() {
std::string day;
std::cout << "Enter day: "; std::getline(std::cin, day);
while (!day.empty()) {
std::cout << day << " --> " << getDayOfWeek(day) << '\n';
std::cout << "Enter day: "; std::getline(std::cin, day);
}
return 0;
}
The "meat" of this is the getDayOfWeek()
function which, given a string, can tell you what day of the week that string represents (if any). Once you have it as an integer, it's a simple matter to use a switch
statement on it, such as:
std::string getDayClass(std::string day) {
switch getDayOfWeek(day) {
case 0: case 6:
return "weekend";
case 1: case 2: case 3: case 4: case 5:
return "weekday";
}
return "unknown";
}
Keep in mind I've used specific rules for decoding the textual day into an integer, checking only the first three characters, and in lowercase,
so WEDDED BLISS
as input will see it thinking it's a Wednesday. Obviously you can make the rules more (or less) restrictive as the situation requires.