Наконец то получилось. Вот код.
#include <iostream>
#include <string>
#include <map>
#include <vector>
using namespace std;
bool shell_finish = false;
map<string, void*> fnMap;
vector<string> explode(string inputstring, string delimiter){
vector<string> explodes;
inputstring.append(delimiter);
while (inputstring.find(delimiter) != string::npos){
explodes.push_back(inputstring.substr(0, inputstring.find(delimiter)));
inputstring.erase(inputstring.begin(), inputstring.begin() + inputstring.find(delimiter) + delimiter.size());
}
return explodes;
}
string trim(const string& str, const string& whitespace = " \t")
{
const auto strBegin = str.find_first_not_of(whitespace);
if (strBegin == string::npos)
return "";
const auto strEnd = str.find_last_not_of(whitespace);
const auto strRange = strEnd - strBegin + 1;
return str.substr(strBegin, strRange);
}
void my_plus(string params) {
double sum = 0;
vector<string> explodes = explode(params, " ");
for (int i = 0; i<(int)explodes.size(); i++){
sum += atof(trim(explodes[i]).c_str());
}
cout << sum << endl;
}
void my_exit(string params = "") {
shell_finish = true;
}
void my_help(string params) {
map<string, string> help;
help["plus"] = "Use following syntax: plus <number_1> <nubmer_2> ...";
help["exit"] = "Exits current shell session.";
if (help.find(params) != help.end()) {
cout << help[params] << endl;
}
else {
cout << "help: command not found" << endl;
}
}
void detect_command(string a) {
fnMap["plus"] = &my_plus;
fnMap["exit"] = &my_exit;
fnMap["help"] = &my_help;
const int arr_length = 10;
string commands[arr_length] = { "plus", "help", "exit" };
string cur_cmd;
for (int i = 0; i < arr_length; i++) {
cur_cmd = commands[i];
if (a.compare(0, cur_cmd.length() + 1, cur_cmd + " ") == 0 || a.compare(0, cur_cmd.length(), cur_cmd) == 0) {
string params = trim(a.substr(cur_cmd.length()));
reinterpret_cast<void(*)(string)>(fnMap[cur_cmd])(params);
break;
}
}
}
int main(void) {
string x;
while (!shell_finish) {
getline(cin, x);
detect_command(x);
}
return 0;
}