获取带有字符串的变量,而不C++中的 if-else
get variable with string without if-else in C++
是否可以使用字符串获取变量的值,以尽量减少大型 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
相关文章:
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 有充分的理由在h文件中使用include保护而不是cpp文件吗
- 为什么使用SFINAE而不是函数重载
- 为什么这个函数将"const char*"转换为"void* const"而不是"const void*"
- 如何将这个C++哈希表转换为动态扩展和收缩,而不是使用硬设置的最大值
- 为什么使用__LINE_的代码在发布模式下在MSVC下编译,而不是在调试模式下
- MSVC是否支持C++11样式的属性而不是__declspec
- CoInitialize()在单独的线程上崩溃而不返回
- 为什么文件名被设置为一个点,而不是在读取矢量中的文件名时
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- GlobalAlloc而不是其他分配方法
- 当比特(而不是字节)的顺序至关重要时的持久性
- 为什么复制而不是移动数据元素?
- 为什么lambda在clang上崩溃而不是在gcc上崩溃
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- () 函子后面的括号,而不是函数指针?
- 为什么是谷神星协方差.计算()似乎永远运行而不返回?
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- 将所有模板类型传递给运算符,而不指定所有类型
- 为什么我们要为avl树实现返回一个指向节点的指针,而不是void函数