将输入从std::cin转换为可运行代码
Converting input from std::cin to runnable code C++
我正在做一个项目,我需要一种方式来接收来自控制台/用户的输入,并使用它来运行代码中的某个部分,而不需要复杂的switch/if:else语句。让我给你举个例子。
#include <iostream>
#include <string>
using namespace std;
void foo();
void foo2();
int main(){
string s;
cin >> s;
/*Take the input from cin and turn it into a function call, or some other
form of runnable code, like so*/
//Lets say the user inputs "run foo"
foo();
//Or if they input "run foo2"
foo2();
return 0;
}
void foo(){
cout << "Foo works, yay :D";
}
void foo2(){
cout << "Foo2 works, yay :D";
}
你可能认为我可以用一个switch或多个if:else语句来实现这一点,但这段代码只是我需要做的事情的一小部分表示。这个项目需要大规模地使用这个,我希望我不需要使用这些,以节省行。
那么在c++中有什么方法可以做到这一点吗?控制台用户告诉程序要运行什么,然后程序运行该函数?
谢谢! !
EDIT这不是要函数调用的字符串的副本,因为它直接从用户而不是从程序获取输入。此外,答案还表明,您可以使用lua来实现,因为来自用户输入。
也许最简单的事情是使用std::function
对象的std::map
:
std::map<std::string, std::function<void()>> funcs;
funcs[userInputString]();
生活例子。
根据你的需求,你可能需要比这更复杂的东西,然而,在某些复杂的点上,你可能想要考虑嵌入一个脚本语言,如Lua。
直接方式:
- 绘制
string
到std::function<void()>
的地图 - 取
cin
输入字符串 - 将
string
按空格扩展为string
数组 - 如果第一个值为"run",则在映射中搜索第二个值,如果找到,则执行函数指针。
参数很难这样实现。
更好的办法:
使用LUA, Squirrel, Angel Code, JS, Python或任何其他可用的C/c++嵌入式语言
typedef void (*ScriptFunction)(void); // function pointer type
typedef std::map<std::string, ScriptFunction> script_map;
void some_function(void)
{
}
script_map m;
m.insert(std::make_pair("blah", &some_function));
void call_script(const std::string& pFunction)
{
script_map::const_iterator iter = m.find(pFunction);
if (iter == m.end())
{
// not found
}
(*iter->second)();
}
call call_script(user_input); in your code
相关文章:
- 如何在linux终端中同时编译和运行c++代码
- 尝试用java代码编译和运行c++代码
- 不同/较旧的处理器运行c++代码的方式是否不同
- 无法在 geany 上运行代码。无法执行构建命令
- 运行代码时,c++ 会终止进程
- 编译多个C++文件.调用二进制文件以运行代码
- 分段故障 运行C++代码时出现 SIGSEGV
- 如何分析在 Windows 上运行C++代码?
- 编译器资源管理器(godbolt)如何安全地运行代码?
- 如何在 vim (windows) 中编译和运行 c++ 代码
- 无法在 Visual Studio 代码中生成和运行 C++ 代码
- 连续运行C++代码和 Python 代码
- 在静态初始化期间运行代码
- C++ .我正在尝试通过使用开关内的数组来获取用户输入,但是当我运行代码时,它显示分段错误?
- 我最近更改了编译器路径以运行 c++ 代码,但现在我无法运行任何 python 代码。我该如何解决这个问题?
- 如何在Visual Studio Code的终端内运行C++代码?
- 在注入的 Dll 的 DllMain 中运行代码导致注入超时
- 并行和顺序运行代码时会产生不同的结果
- 运行代码时C++错误
- 在 CortexM0 中从 RAM 运行代码时出现硬故障