用c++编写命令行接口的更好方法是什么
Whats a better way to code a command line interface in c++?
我使用的是普通的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中已经过时了)。这只是一个想法的快速草图,而不是任何接近完成代码的东西。
相关文章:
- 初始化具有非默认构造函数的std::数组项的更好方法
- Protobuf中重复字段的问题.使用重复字段进行序列化/反序列化的更好方法是什么?
- 编写按初始值循环的循环的更好方法是什么
- 用 c++ 为游戏制作"bullet"的更好方法?
- 在CMakeLists中包含目录的更好方法.txt
- 将QDomDocument数据用作文本的更好方法
- C++ - 创建具有相同字符的特定大小的以 null 结尾的 c 样式字符串的更好方法
- 在 sqlite3 中批量插入的更好方法C++
- 设计许多单例代码结构的更好方法
- 使用继承的类模板避免公共成员不可见和源代码膨胀/重复的更好方法
- 在初始化列表中初始化数组的更好方法
- 将对象从一个 std::d eque 移动到另一个的更好方法
- 请告诉我在巴泽尔拥有多平台工作空间的更好方法
- 构造具有大量数据的对象的更好方法(C++)
- 从2D矢量中找出最小尺寸的向量元素的更好方法
- 在C++中创建不可变对象的更好方法
- 在构造函数中组织初始值设定项列表的更好方法
- std::copy with return values - 防止"expression: string iterators incompatible"的更好方法?
- 删除数组成员的更好方法是什么?
- 在C 中操作数据的更好方法是什么