Skip to content

Instantly share code, notes, and snippets.

@Fiona-J-W
Created March 24, 2015 02:07
Show Gist options
  • Save Fiona-J-W/edbdf6b91e0fb1f24e71 to your computer and use it in GitHub Desktop.
Save Fiona-J-W/edbdf6b91e0fb1f24e71 to your computer and use it in GitHub Desktop.
Calling function based on user-input
#include <algorithm>
#include <string>
#include <stdexcept>
#include <vector>
#include <iostream>
#include <cmath>
#include <unordered_map>
#include <functional>
#include <iterator>
void print(const std::vector<std::string>& args) {
std::copy(args.begin(), args.end(), std::ostream_iterator<std::string>{std::cout, "\n"});
}
void print_sqrt(const std::vector<std::string>& args) {
if (args.size() != 1) {
throw std::runtime_error{"sqrt must get exactly one argument"};
}
std::cout << std::sqrt(std::stod(args.front())) << '\n';
}
void print_square(const std::vector<std::string>& args) {
if (args.size() != 1) {
throw std::runtime_error{"sqare must get exactly one argument"};
}
const auto val = std::stod(args.front());
std::cout << val* val << '\n';
}
void print_sum(const std::vector<std::string>& args) {
const auto op = [](double val, const std::string& str) { return val + std::stod(str); };
std::cout << std::accumulate(args.begin(), args.end(), 0.0, op) << '\n';
}
void print_product(const std::vector<std::string>& args) {
const auto op = [](double val, const std::string& str) { return val * std::stod(str); };
std::cout << std::accumulate(args.begin(), args.end(), 1.0, op) << '\n';
}
int main(int argc, char** argv) try {
if (argc < 2) {
std::cerr << "Error: At least one argument required.\n";
return 1;
}
const auto fun = std::string{argv[1]};
const auto args = std::vector<std::string>(argv + 2, argv + argc);
const auto function_map =
std::unordered_map<std::string,
std::function<void(const std::vector<std::string>&)>>{
{"print", print},
{"sqrt", print_sqrt},
{"square", print_square},
{"+", print_sum},
{"*", print_product}};
const auto it = function_map.find(fun);
if (it == function_map.end()) {
std::cerr << "Error: No such function.\n";
return 2;
}
it->second(args);
} catch (std::runtime_error& e) {
std::cerr << "Error: " << e.what() << '\n';
return 3;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment