C++中的切换案例 [英] Switch Case in c++
问题描述
如何使用 switch-case 比较 C++ 中的字符数组?这是我的代码的一部分:
How can I compare an array of char in c++ using switch-case? Here is a part of my code:
char[256] buff;
switch(buff){
case "Name": printf("%s",buff);
break;
case "Number": printf("Number "%s",buff);
break;
defaul : break
}
我收到错误:错误:开关数量不是整数".我该如何解决?
I receive the error :" error: switch quantity not an integer".How can I resolve it?
推荐答案
如果您确实需要 switch 语句,则需要将 buff
变量转换为整数.为此,您可以使用哈希函数或 std::map
.
If you really need a switch statement, you will need to convert your buff
variable to an integer. To do so, you could use a hash function or a std::map
.
简单的方法是制作一个 std::map<std::string,int>
,其中包含您要在与唯一 int
价值观.你会得到类似的东西:
The easy approach would be to make a std::map<std::string,int>
containing the keys you want to use in the switch associated with unique int
values. You would get something like:
std::map<string,int> switchmap;
...
switch(switchmap.find(std::string(buff))->second){
...
}
std::map
方法非常易读,不会引起太多混淆.
The std::map
approach is very readable and shouldn't cause much confusion.
这篇关于C++中的切换案例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!