在控制台应用程序中解析命令

Parsing commands in a console application

所以我的控制台应用程序是基于命令的,例如用户可以输入 "connect 127.0.0.1" 它会做一些事情。我已经能够将命令与参数分开,但是我如何让它根据命令字符串调用函数,并使命令与对应的字符串相匹配?

使用标准 parsing 技术,并阅读来自 std::cin

的命令

您可能想要声明参数向量的类型。

typedef std::vector<std::string> vectarg_T;

声明函数处理命令的类型:

typedef std::function<void(vectarg_T)> commandprocess_T;

并有一个将命令名称与其处理器相关联的映射:

std::map<std::string,commandprocess_T> commandmap;

然后在初始化时填充该地图,例如使用匿名函数:

 commandmap["echo"] = [&](vectarg_T args){ 
    int cnt=0;
    for (auto& curarg: args) { 
      if (cnt++ > 0)   std::cout << ' ';
      std::cout << curarg;
    }
    std::cout << std::endl;
 };

如果您的问题是关于解析程序参数(main),请使用 getopt(3) and related functions. GNU libc providesargp_parse

考虑 或许 嵌入一个 interpreter in your program, e.g. embedding GNU Guile or Lua. But embedding an interpreter is an important architectural design decision and should be made early. Then your application becomes Turing-complete.

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main(int argc, const char * argv[]) {

    map<string,string> commands;
    cout<<argc<<endl;
    for(int i=1;i<=argc/2;i++)
    {
        string cmd =argv[i*2-1];
        string param =argv[i*2];
        cout<<cmd<<endl;
    }
    string ip = commands["connect"];
    cout<<"are you want to connect "<<ip<<" ?";
    return 0;
}