switch的参数不能是string float?

Greg_han 2009-09-25 09:47:44
#include<string>
#include<iostream>
using namespace std;

int main()
{
string ss;
cout<<"请出入串ss:"<<endl;
cin>>ss;
cout<<endl;

switch(string ss)
{
case "asd":
int *a=new int[2];
break;
case "zxc":
float *f=new float[2];
break;
}

return 1;
}

出现编译错误,听说是 switch的参数不能是 string,float 等类型,为什么哪?如何解决上述代码?
...全文
2280 20 打赏 收藏 转发到动态 举报
写回复
用AI写文章
20 条回复
切换为时间正序
请发表友善的回复…
发表回复
jeryhe 2011-03-29
  • 打赏
  • 举报
回复
刚刚还在为它纠结呢,可不可以用指针数组嵌套
Jerry_Lee01 2011-01-19
  • 打赏
  • 举报
回复
switch的参数只能是是整形,或者可以无二意转化为整形的类型,如byte,char,short,int,其他的不能识别。用else if是一个解决办法!
weizy2288 2010-12-29
  • 打赏
  • 举报
回复
早该结贴了吧
shi51314 2010-09-09
  • 打赏
  • 举报
回复
The C++ switch statement allows selection among multiple sections of code, depending on the value of an expression. The expression enclosed in parentheses, the “controlling expression,” must be of an integral type or of a class type for which there is an unambiguous conversion to integral type
shi51314 2010-09-09
  • 打赏
  • 举报
回复
switch参数只能是整形,或者可以无二意转化为整形的类型
cjf271 2010-03-22
  • 打赏
  • 举报
回复
14.不能做switch()的参数类型是:
switch的参数不能为实型。
liyanlin122 2010-03-15
  • 打赏
  • 举报
回复
学习了
Johnny_Lx 2009-09-26
  • 打赏
  • 举报
回复
楼主可以用map<int , string> 这样的键值对来做,每个字符串给他一个特定的key,然后对key做switch...case...
lihan6415151528 2009-09-26
  • 打赏
  • 举报
回复
switch 的参数只能是byte,char,short,int型的

string 不适合用在这里
建议用if语句解决问题
xmrforever 2009-09-26
  • 打赏
  • 举报
回复
LZ可以结贴了
cheng_fengming 2009-09-26
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 jgood 的回复:]
switch参数只能是整形。
[/Quote]
是的
loveour 2009-09-26
  • 打赏
  • 举报
回复
switch()括号内只能为整形,字符型,还有枚举,解决办法使用嵌套的if else。
其实switch本身也是帮助人去使用if else的,算是一个功能特化的if else吧,貌似编译后就是嵌套的if else
zenny_chen 2009-09-26
  • 打赏
  • 举报
回复
[Quote=引用楼主 greg_han 的回复:]
#include <string>
#include <iostream>
using namespace std;

int main()
{
string ss;
cout < <"请出入串ss:" < <endl;
cin>>ss;
cout < <endl;

switch(string ss)
{
case "asd":
int *a=new int[2];
break;
case "zxc":
float *f=new float[2];
break;
}

return 1;
}

出现编译错误,听说是 switch的参数不能是 string,float 等类型,为什么哪?如何解决上述代码?
[/Quote]
用if-else啊,呵呵。

[Quote=引用 7 楼 zgjxwl 的回复:]
自己看MSDN吧。。。
[/Quote]
还是参考C/C++标准比较好。
zgjxwl 2009-09-26
  • 打赏
  • 举报
回复
自己看MSDN吧。。。
zgjxwl 2009-09-26
  • 打赏
  • 举报
回复
这实际是关系到比较的问题了。。。。对于float,不能用==之类比较

对于char*也不能用==比较。。。而是用strcmp比较。。。

原因应该就是上面的吧
wanjingwei 2009-09-25
  • 打赏
  • 举报
回复
可以自己写个函数
int fun(.....)
{
if(ss=="asd")return 1;
if(ss=="zxc")return 2;
.........
}
wanjingwei 2009-09-25
  • 打赏
  • 举报
回复
switch 的参数只能是byte,char,short,int型的
lsldd 2009-09-25
  • 打赏
  • 举报
回复
确实不能。。。
解决办法之一是使用一堆if---else...
JGood 2009-09-25
  • 打赏
  • 举报
回复
使用if..else if...else吧
JGood 2009-09-25
  • 打赏
  • 举报
回复
switch参数只能是整形。

64,639

社区成员

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

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