接收字符串并使用它来调用方法C ++

时间:2018-10-19 12:20:26

标签: c++ json

  • 我有一个来自客户端的字符串(来自Json),现在我想 破坏它,以便我可以将第一部分用作函数,而将其他部分用作参数,依此类推。
  • 为了更清楚地说明这一点,我有一个字符串“ PRINT ARTIFACTS 10”。
  • 现在,我想使用PRINT来调用函数AND“ ARTIFACTS”,“ 10”作为该函数中的参数。

现在我正在这样做: 客户端:(python)

data = json.dumps({"A":"PRINT","B":"ARTIFACTS","C":10})
s.send(data)

服务器端:(C ++)

recv(newSd, (char*)&msg, sizeof(msg), 0);
string str(msg);
string text = msg;
bool parsingSuccessful = reader.parse( text, root );
if  ((root["A"] == "PRINT") &&
            (root["B"]== "ARTIFACTS")&&
            (root["C"]==10)){
                PRINT(ARTIFICATS,10);
            }

我知道这不是帮助我的正确方法。

谢谢。

1 个答案:

答案 0 :(得分:6)

您可以使用unordered_map实现从命令字符串到处理该命令的函数的实现的映射。

示例实现可以按如下方式工作:

// A function handler takes its arguments as strings and returns some sort of result
// that can be returned to the user. 
using CommandHandler = std::function<Result(std::vector<std::string> const&)>

// various handers for command requests
Result handle_print(std::vector<std::string> const& args);
Result handle_delete(std::vector<std::string> const& args);
Result handle_add(std::vector<std::string> const& args);
Result handle_version(std::vector<std::string> const& args);

// the table that holds our commands
std::unordered_map<string, CommandHandler> command_table = {
    {"print", handle_print},
    {"delete", handle_delete},
    {"add", handle_add},
    {"version", handle_version},
};

// take your json doucment, extract the first value as the command, and put the rest into an arg array: 

void handle_request(Connection& connection, json const& request)
{
    std::string cmd = root["A"];
    std::vector<std:string> args;
    // parse the rest of your arguments into an array here. 

    if(command_table.count(cmd))
    {
        // command is valid
        auto& handler = command_table[cmd];
        auto result = handler(args);
        send_result(connection, result);
    }
    else
    {
        // send bad command error or something

        send_bad_command(connection);
    }
}
相关问题