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

2019-08-22 14:33发布

问题:

This question already has an answer here:

  • Calling a Function From a String With the Function’s Name in C++ 8 answers

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

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.

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?

Thanks!!

EDIT This is not a duplicate of the string to function call as this gets the input directly from the user versus from the program. As well as the answers show that you can use lua to do this since it is from user input.

回答1:

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]();

Live example.

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.



回答2:

Straight-forward way:

  • Make a map of string to std::function<void()>
  • Take the cin input string
  • Explode the string by spaces to a string array
  • If the first value is "run", Search the map for the second value and if you find it, execute the function pointer.

Arguments are hard to implement this way.

Better way:

Use LUA, Squirrel, Angel Code, JS, Python, or any other C/C++ embedded language available.



回答3:

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


标签: c++ c++11 input