将输入从std::cin转换为可运行代码

Converting input from std::cin to runnable code C++

本文关键字:运行 代码 转换 cin 输入 std      更新时间:2023-10-16

我正在做一个项目,我需要一种方式来接收来自控制台/用户的输入,并使用它来运行代码中的某个部分,而不需要复杂的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。

直接方式:

  • 绘制stringstd::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