在C++中有没有一种方法可以在switch语句中使用字符串?

6

目前我正在尝试使用字符串switch获取用户输入,但编译器产生了异常并带有未知错误关闭。

这是我正在尝试的代码:

#include <iostream>
using namespace std;
int main()
{
   string day;
   cout << "Enter The Number of the Day between 1 to 7 ";
   cin >> day;
  switch (day) {
  case 1:
    cout << "Monday";
    break;
  case 2:
    cout << "Tuesday";
    break;
  case 3:
    cout << "Wednesday";
    break;
  case 4:
    cout << "Thursday";
    break;
  case 5:
    cout << "Friday";
    break;
  case 6:
    cout << "Saturday";
    break;
  case 7:
    cout << "Sunday";
    break;
default:
    cout << "Attention, you have not chosen the Valid number to Identify weekly days from 1 to 7. Try again!" << endl;
 }

}
2个回答

8

在 switch 语句中不能使用字符串,在这个简单的例子中,您可以将 string day; 替换为 int day;。如果变量必须是字符串,您可以将其转换为整数,有几种工具可供使用,例如 strtolstoi


8

string day替换为int day,或者在进入switch之前,将daystring转换为int,例如使用std::stoi()进行转换。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接