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

时间:2020-01-30 15:36:15

标签: c++

当前,我正在尝试通过将 string 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 个答案:

答案 0 :(得分:7)

string day;替换为int day;

答案 1 :(得分:7)

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