【发布时间】:2013-04-29 14:30:09
【问题描述】:
我想用开关评估一个字符串,但是当我读取用户输入的字符串时,我会抛出以下错误。
#include<iostream>
using namespace std;
int main() {
string a;
cin>>a;
switch (string(a)) {
case "Option 1":
cout<<"It pressed number 1"<<endl;
break;
case "Option 2":
cout<<"It pressed number 2"<<endl;
break;
case "Option 3":
cout<<"It pressed number 3"<<endl;
break;
default:
cout<<"She put no choice"<<endl;
break;
}
return 0;
}
错误:从类型“std::string {aka std::basic_string}”到类型“int”的无效转换
【问题讨论】:
-
std::string不适用于 switch。 -
Switch 表达式的计算结果必须为整数类型。
-
hash the string 如果你真的想要的话。 Some hashing algorithm。或者你能不能只得到选项编号,即 1、2、3、...?
-
if (a >= "Option 1" && a <= "Option 3") {std::cout << "It pressed number " + std::string(a.rbegin(), a.rbegin() + 1) << '\n';} else {std::cout << "She put no choice\n";} -
@antitrust:不,同样,
try/catch不会保护 UB。在访问字符之前,您需要使用if测试长度。或者您是否在考虑边界检查的at()方法而不是未检查的operator[]()?
标签: c++