Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an Interactive Prompt in C++

I have a program which should read commands from the console and depending on the command perform one of several actions. Here is what I have so far:

void ConwayView::listening_commands() {
    string command;

    do {
        cin >> command;

        if ("tick" == command)
        {
            // to do
        }
        else if ("start" == command)
        {
            // to do for start
        }
        ...

    } while (EXIT != command);
}

Using a switch in place of the if statements helps a little if there are a large amount of commands. What patterns do you suggest using to provide the interactive command line?

like image 505
Dima00782 Avatar asked Oct 22 '22 02:10

Dima00782


1 Answers

There are multiple ways to solve this and it's debatable what the "right" solution is. If I were to solve it for my own work, I would create a table of a custom struct. Something like:

struct CommandStruct {
    char *command;
    int (*commandHandler)(/*params*/);
} commandTable[] = {
    { "tick",  tickCommand },
    { "start", startCommand },
    ...
};

Then my processing loop would walk through each element of this table, looking for the right match, such as:

for (int i = 0; i < TABLE_SIZE; ++i) {
    if (command == commandTable[i].command) { /* using whatever proper comparison is, of course */
        commandTable[i].commandHandler(/*params*/);
        break;
    }
}
like image 136
mah Avatar answered Oct 26 '22 22:10

mah