用c++编写命令行接口的更好方法是什么

Whats a better way to code a command line interface in c++?

本文关键字:更好 方法 是什么 命令行接口 c++      更新时间:2023-10-16

我使用的是普通的C++,我正在构建一个小的"Zork esc";游戏作为一个宠物项目来锻炼我新学到的C++技能。下面的代码运行得很好,但是对于每个命令/参数组合都必须这样做会很痛苦,所以如果有人能给我省去一些麻烦,请这样做:D。。。

目前,我有这个函数负责在运行时处理命令。。。

void execute()
{
    //###### Command builder ######
    cout << ">>>";
    char input[100];
    cin.getline(input, sizeof(input));
    cout << input << endl;
    string newin = input;
    //###### Execution Phase ######
    if(newin=="derp"){
        // normally functions go here
        cout << "You did it :D" << endl;
    }else if(newin=="attack player1 player2"){
        // normally functions go here
        cout << "player1 attacks player2" << endl;
    }else{
        // quriky error message for the user
        cout << "dafuq?" << endl;
    }
    execute();
}

它接受你的输入并将其与所有可能的字符串组合进行比较,当它找到匹配项时,它假设运行放置在IF雄蕊中的相应函数

就像我说的那样,它有效,但我觉得还有很大的改进空间。。。

编辑

我基本上是在移植我用python制作的程序,用那种语言我花了三行10分钟才弄清楚。

我使用了带有一些字符串的eval()函数,这样我就可以使用标准的"name(arg)";总体安排它基本上只是评估了我的字符串并运行了函数,就像这样。。。

def execute(arg):
    try:
        eval(arg)
    except TypeError:
        print('=====## Alert ##=========================================================')
        print('You must provide the arguments in the parentheses')
        print('=========================================================================')
    except SyntaxError:
        print('=====## Alert ##=========================================================')
        print('I didn't understand that D:')
        print('=========================================================================')

因此,如果我有一个名为attack()的函数,它接受两个参数";播放器1";以及";播放器2";我可以把它键入提示";攻击(播放器1、播放器2)";它会运行它,就像我在代码体中键入了确切的东西来运行它一样。那么,有没有一种方法可以让c++像计算代码一样计算字符串呢?喜欢

字符串derp=";攻击(播放器1、播放器2)";

您可以考虑使用映射(可能是std::unordered_map)…从输入映射到适当的操作:

std::unordered_map<std::string, std::unary_function *> actions;
class attack : public std::unary_function /*... */
class flee : public std::unary_function /* ... */
action["attack"] = attack;
action["flee"] = flee;
// ...

当然,您可以得到比仅仅使用unary_function更复杂的东西(它在C++11中已经过时了)。这只是一个想法的快速草图,而不是任何接近完成代码的东西。