Home > Blockchain >  How do I make it so that choosing a certain "directory" calls a function?
How do I make it so that choosing a certain "directory" calls a function?

Time:11-02

You know how this shows up when you choose a directory in the terminal?

choosing a directory on terminal

Is there a way I could create my own version of this, but when the user chooses one of the choices, it calls a function?

I don't need to be a directory but if the user says like

"options"

that menu pops up and it lists

"games" "text" "about"

can type

"open games"

void game()
{
    cout << "you are in game"
}

void text()
{
    cout << "you are in text"
}

void about()
{
    cout << "you are in about"

this is all i want it to do before int main() (for now, ofc)

how do i make it so that a certain input LISTS the different functions, and a certain input calls the different functions?

CodePudding user response:

I have understood that you want to see a list of functions in your program, not files on your hard disk.

There's no built-in way to do this, and although I can think of some more clever ways to do it, they are beyond your current level of understanding.

Therefore, I recommend doing it the simple and stupid way:

while(true) {
    string input;
    getline(cin, input);
    if(input == "open games")
        games();
    else if(input == "open text")
        text();
    else if(input == "open about")
        about();
    else if(input == "options")
        cout << "games text about\n";
    else
        cout << "unknown command\n";
}

CodePudding user response:

You've got two wishes: you want to store a list of functions with names, and in addition you want to be able to retrieve the whole list of names.

The type that you probably want is std::map<std::string, std::function<void(void)>>.

E.g.

std::map<std::string, std::function<void(void)>> options;
options["game"] = game;

std::map stores key-value pairs. The key here is the string, the value is the function. You can iterate over options and print all the keys. See your C book for more details.

  • Related