将输入从std :: cin转换为可运行代码C ++ [英] Converting input from std::cin to runnable code C++

查看:204
本文介绍了将输入从std :: cin转换为可运行代码C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个项目,我需要一种方法从控制台/用户接收输入,并使用它来运行代码中的某个部分,而不需要精心设计的开关/ if:else语句。让我举个例子。

I'm working on a project and I need a way of receiving input from the console/user and use that to run a certain part in the code without the need of elaborate switch/if:else statements. Let me give you an example.

#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";
}

你可能认为我可以用一个开关或多个if:else语句但这个小代码只是我需要做的一个小代表。该项目需要这个大规模使用,如果我不需要使用这些,以节省行。我希望它。

You might think I could do this with a switch or multiple if:else statements but this little code is just a small representation of what I need to do. The project requires this to be used on a large scale and I'd like it if I didn't need to use those, to save lines.

方式我可以在C ++中做到这一点?

So is there any way I can do this in C++? Where the console user tells the program what to run and it runs said function?

谢谢!

推荐答案

此外,

也许最简单的事情是使用 std :: function objects: std :: map / p>

Maybe the simplest thing would be to use a std::map of std::function objects:

std::map<std::string, std::function<void()>> funcs;
funcs[userInputString]();

活动示例

根据您的需求,您可能需要比这更复杂的东西,但在某些复杂性,你可能想考虑嵌入脚本语言像Lua。

Depending on your requirements you may need something more sophisticated than this however and at some point of complexity you might want to consider embedding a scripting language like Lua.

这篇关于将输入从std :: cin转换为可运行代码C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆