cpp switch 字符
时间: 2023-07-28 18:51:50 浏览: 48
C++中的switch语句除了可以用于整型变量外,也可以用于字符变量。基本语法与使用整型变量时类似,只需将case后的常量表达式改为字符即可。
示例代码:
```cpp
#include <iostream>
using namespace std;
int main() {
char grade = 'B';
switch (grade) {
case 'A':
cout << "Excellent";
break;
case 'B':
case 'C':
cout << "Well done";
break;
case 'D':
cout << "You passed";
break;
case 'F':
cout << "Better try again";
break;
default:
cout << "Invalid grade";
}
return 0;
}
```
输出结果为:"Well done",因为当grade等于'B'或'C'时,执行的是同一个语句块。
相关问题
switch字符串比较
在 C++ 中,switch 语句是不能直接使用字符串进行比较的。但可以使用一些技巧来实现类似 switch 字符串比较的功能,比如使用哈希表或者枚举类型。
下面是使用哈希表实现 switch 字符串比较的示例代码:
```cpp
#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
string str;
cin >> str;
unordered_map<string, int> mp = {{"apple", 1}, {"banana", 2}, {"orange", 3}};
if (mp.count(str)) {
switch (mp[str]) {
case 1:
cout << "It's an apple." << endl;
break;
case 2:
cout << "It's a banana." << endl;
break;
case 3:
cout << "It's an orange." << endl;
break;
}
} else {
cout << "Unknown fruit." << endl;
}
return 0;
}
```
cpp几的switch可以判断字符串吗
在C++11之前,switch语句只能判断整数类型的常量表达式,不能直接用于字符串。但可以使用if-else语句或者map容器等方式实现字符串的判断。
从C++11开始,可以使用switch语句对字符串进行判断,需要使用字符串字面值常量作为case标签,并使用std::string的hash函数作为switch表达式。示例代码如下:
```c++
#include <iostream>
#include <string>
int main() {
std::string str = "hello";
switch (std::hash<std::string>{}(str)) {
case std::hash<std::string>{}("hello"):
std::cout << "Hello World!\n";
break;
case std::hash<std::string>{}("world"):
std::cout << "Goodbye World!\n";
break;
default:
std::cout << "Unknown string!\n";
break;
}
return 0;
}
```
注意,使用字符串的hash值作为switch表达式可能会导致碰撞(即多个不同的字符串具有相同的hash值),因此需要对字符串进行一定的处理,例如忽略大小写、去除空格等,以避免误判。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)