本文介绍了使用C ++中的开关来评估字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我想评估一个带有开关的字符串,但是当我读取用户输入的字符串时,会引发以下错误。I want to evaluate a string with a switch but when I read the string entered by the user throws me the following error.#include<iostream>using namespace std; int main() { string a; cin>>a; switch (string(a)) { case "Option 1": cout<<"It pressed number 1"<<endl; break; case "Option 2": cout<<"It pressed number 2"<<endl; break; case "Option 3": cout<<"It pressed number 3"<<endl; break; default: cout<<"She put no choice"<<endl; break; } return 0; } 推荐答案 ,开关只能使用整数值。所以,你只需要将你的case值转换为整数。您可以通过使用来自c ++ 11的 constexpr 来实现它,从而可以计算一些constexpr函数的调用在编译时。As said before, switch can be used only with integer values. So, you just need to convert your "case" values to integer. You can achieve it by using constexpr from c++11, thus some calls of constexpr functions can be calculated in compile time.这样的... switch (str2int(s)){ case str2int("Value1"): break; case str2int("Value2"): break;}其中str2int是(从在这里):where str2int is like (implementation from here):constexpr unsigned int str2int(const char* str, int h = 0){ return !str[h] ? 5381 : (str2int(str, h+1) * 33) ^ str[h];} Another example, the next function can be calculated in compile time:constexpr int factorial(int n){ return n <= 1 ? 1 : (n * factorial(n-1));} int f5{factorial(5)};// Compiler will run factorial(5) // and f5 will be initialized by this value. // so programm instead of wasting time for running function, // just will put the precalculated constant to f5 这篇关于使用C ++中的开关来评估字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 11-03 10:25