C++编写程序,使用switch语句,将输入的数字(1-7)转换成对应的星期英文名称输出
时间: 2024-11-30 15:16:53 浏览: 26
在C++中,你可以使用`switch`语句结合`enum`来实现这个功能。首先,你需要创建一个枚举类型,表示一周的天数,然后通过输入值匹配相应的字符串。以下是示例代码:
```cpp
#include <iostream>
using namespace std;
enum class WeekDays {
Monday = 1,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
};
WeekDays getDayOfWeek(int input) {
switch (input) {
case 1:
return WeekDays::Monday;
case 2:
return WeekDays::Tuesday;
case 3:
return WeekDays::Wednesday;
case 4:
return WeekDays::Thursday;
case 5:
return WeekDays::Friday;
case 6:
return WeekDays::Saturday;
case 7:
return WeekDays::Sunday;
default:
cout << "Invalid input! Please enter a number between 1 and 7." << endl;
return WeekDays::Monday; // 返回默认的第一天,以处理无效输入
}
}
int main() {
int userInput;
cout << "Enter a number between 1 and 7 to represent the week day: ";
cin >> userInput;
WeekDays day = getDayOfWeek(userInput);
cout << "The corresponding day is: " << static_cast<string>(day) << endl; // 转换枚举为字符串输出
return 0;
}
```
阅读全文