Reputation: 903
So my console application is based around commands, for example a user could enter "connect 127.0.0.1" and it would do stuff. I already am able to separate commands from arguments, but how would I make it call a function based on the command string, and have something to match commands to their string counterparts?
Upvotes: 0
Views: 279
Reputation: 1
#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;
}
Upvotes: 0
Reputation: 1
Use standard parsing techniques, and read commands from std::cin
You might want to declare a type for the vector of arguments.
typedef std::vector<std::string> vectarg_T;
declare a type for functions processing commands:
typedef std::function<void(vectarg_T)> commandprocess_T;
and have a map associating command names to their processors:
std::map<std::string,commandprocess_T> commandmap;
then fill that map at initialization time, e.g. using anonymous functions:
commandmap["echo"] = [&](vectarg_T args){
int cnt=0;
for (auto& curarg: args) {
if (cnt++ > 0) std::cout << ' ';
std::cout << curarg;
}
std::cout << std::endl;
};
If your question is about parsing program arguments (of main
), use getopt(3) and related functions. GNU libc provides also argp_parse
.
Consider perhaps instead embedding an 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.
Upvotes: 1