lundi 31 août 2015

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

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!!

Aucun commentaire:

Enregistrer un commentaire