c++ switch字符串
时间: 2023-12-31 10:20:58 浏览: 58
在 C++ 中,switch 语句只能用于整型、字符型和枚举类型的变量,不能直接用于字符串。但是可以通过将字符串转换为整型或枚举类型来实现类似的功能。例如,可以使用哈希函数将字符串映射为整型,然后在 switch 语句中使用该整型。
以下是一个示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
int hash_func(string str) {
int hash_val = 0;
for (char c : str) {
hash_val += c;
}
return hash_val;
}
int main() {
string str = "hello";
int hash_val = hash_func(str);
switch (hash_val) {
case hash_func("hello"):
cout << "Hello, world!" << endl;
break;
case hash_func("world"):
cout << "World, hello!" << endl;
break;
default:
cout << "Unknown string!" << endl;
break;
}
return 0;
}
```