switch为什么不能用string类型?怎样解决?

yk3229319 2011-08-04 09:46:25
代码如下:

#include<iosteram>
#include<string>
using namespace std;

int main()
{
string str;
switch (str)
{
case 'ab':
cout << 'true';
default:
cout << "erroe";
}
return 0;
}
...全文
12597 12 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
ahumoon7421 2011-08-05
  • 打赏
  • 举报
回复
可以定义枚举型,间接实现;可以如3楼所言,用map容器;可以用hash函数,用函数返回值作条件;用strcmp来作条件(原理同hash函数法)etc...
东莞某某某 2011-08-04
  • 打赏
  • 举报
回复
对 C#可以 还什么都封装了
Jxiaoshen 2011-08-04
  • 打赏
  • 举报
回复
switch的参数不可以是string。switch是用"="进行比较,而string没有"="的概念,只有strcmp

#include<iosteram> ---》
#include<iostream>
liutengfeigo 2011-08-04
  • 打赏
  • 举报
回复
你写if不行啊
机智的呆呆 2011-08-04
  • 打赏
  • 举报
回复
换c#吧 c#支持switch字符串
机智的呆呆 2011-08-04
  • 打赏
  • 举报
回复
The condition shall be of integral type, enumeration type, or of a class type for which a single conversion function to integral or enumeration type exists (12.3). If the condition is of class type, the condition is converted
by calling that conversion function, and the result of the conversion is used in place of the originalcondition for the remainder of this section.

c++规定switch后面只能是 整型、枚举和重载了强制转换整型枚举函数的类 类型。
机智的呆呆 2011-08-04
  • 打赏
  • 举报
回复 1
因为string中木有重载operator int()

#include <iostream>
using namespace std;

class MyString
{
public:
operator int()
{
return 2;
}
};
int main()
{
MyString s;
switch(s)
{
case 2:
cout<<"ss"<<endl;
}
}

Michael_Xie 2011-08-04
  • 打赏
  • 举报
回复
typedef void (*fntptr)(string);
map<string, fntptr> m;
m.insert(pair("a", funA));
m.insert(pair("b", funB));
...
m["a"](...);
hongwenjun 2011-08-04
  • 打赏
  • 举报
回复
switch (expression)  // 括号里是一个表达式,结果是个整数
{
case constant1: // case 后面的标号,也是个整数
group of statements 1;
break;
case constant2:
group of statements 2;
break;
.
.
.
default:
default group of statements
}
luciferisnotsatan 2011-08-04
  • 打赏
  • 举报
回复
规定

只能是整型。
C++可以用个map
#const int STR_AB = 1;
map<string,int> mp;
mp["ab"] = STR_AB;

switch (mp[str])
{
case STR_AB:
...
}
無_1024 2011-08-04
  • 打赏
  • 举报
回复
解决办法就是用if elseif elseif else
代替
無_1024 2011-08-04
  • 打赏
  • 举报
回复
switch()括号里面的参数是一个int型值啊 你要可以转换为int型的参数才行得通啊

65,196

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧