【问题标题】:Is there a way in C++ to use string with switch Statement? [duplicate]C++ 中有没有办法将字符串与 switch 语句一起使用? [复制]
【发布时间】:2020-01-30 15:36:15
【问题描述】:

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

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

}

【问题讨论】:

    标签: c++


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      不能在 switch 语句中使用字符串,在这个简单的示例中,您可以将 string day; 替换为 int day;。如果变量必须是字符串,您始终可以将其转换为 int,您可以使用多种工具来完成此操作,strtolstoi 仅举几例。

      【讨论】:

        猜你喜欢
        • 2021-01-25
        • 2012-10-24
        • 2016-12-23
        • 2012-10-30
        • 1970-01-01
        • 1970-01-01
        • 2020-03-18
        • 1970-01-01
        • 2023-03-15
        相关资源
        最近更新 更多