C++ 中有没有办法在 switch 语句中使用字符串?

Саш*_*аша 6 c++

目前我正在尝试通过使用带有switch 的string来获取用户输入,但是编译器很生气,它给出了一个异常,并以一个未知错误关闭。这是我正在尝试的代码。

#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;
 }

}
Run Code Online (Sandbox Code Playgroud)

ana*_*ciu 8

不可能在 switch 语句中使用字符串,在这个简单的例子中,你可以string day;int day;. 如果变量必须是你可以随时将其转换为一个int一个字符串,有几个工具可以帮助您这样做,strtolstoi命名一对夫妇。


Jam*_*esS 8

替换string dayint day,或者在您进入之前switchday从 a转换stringint诸如 with std::stoi()