获取带有字符串的变量,而不C++中的 if-else

get variable with string without if-else in C++

本文关键字:而不 C++ 中的 if-else 变量 字符串 获取      更新时间:2023-10-16

是否可以使用字符串获取变量的值,以尽量减少大型 if-else 语句的使用。例如:

string a = "hello world";
string b = "foo";
string input;
cout << "a or b";
cin >> input;
//is something like the next line possible?
cout << "your answer is equal to " << string_to_variable(input) << endl;

如果用户输入"A",这应该输出"hello world",如果用户输入"b",则输出"foo"。

谢谢。

是否可以使用字符串获取变量的值,以最大程度地减少大型 if-else 语句的使用。

您可以使用std:map<std::string, std::string>使编程更容易,但在此之下,它仍然使用大量比较和if-else类型检查。

std::map<std::string, std::string>> mymap = {{"a", "hello world"}, {"b", "foo"}};
std::string input;
cout << "a or b";
cin >> input;
//is something like the next line possible?
cout << "your answer is equal to " << maymap[input] << endl;

如果希望代码更精确,可以使用:

auto it = mymap.find(input);
if ( it == mymap.end() )
{
   cout << "There is no answer corresponding to " << input << endl;
}
else
{
   cout << "your answer is equal to " << it->second << endl;
}

而不是

cout << "your answer is equal to " << maymap[input] << endl;

a 和 b 是仅存在于源代码中的变量名称,在运行时不可用。要完成您正在寻找的内容,请尝试创建从输入字符串到输出字符串的映射。

map<string, string> inputMapping;
inputMapping["a"] = "hello world";
inputMapping["b"] = "foo";
string input;
cout << "a or b";
cin >> input;
result = inputMapping[input];
cout << "your answer is equal to " << result << endl;

请注意,理想情况下,您希望执行一些输入清理,并且可能使用inputMapping.find而不是[]运算符来识别何时获得未知输入。通过此设置,您可以支持任意数量的输入字符串来匹配并在整个程序中动态添加它们。您可以在此处了解有关地图的更多信息:http://en.cppreference.com/w/cpp/container/map