fork download
  1. #include <iostream>
  2. #include <sstream>
  3. #include <iterator>
  4. #include <vector>
  5. #include <string>
  6. #include <unordered_map>
  7. #include <memory>
  8.  
  9.  
  10. struct command {
  11.  
  12. using args_type = std::vector<std::string>;
  13.  
  14. virtual void exec(args_type const& args) const = 0;
  15.  
  16. virtual ~command() {}
  17. };
  18.  
  19. struct read_file : command {
  20.  
  21. virtual void exec(args_type const& args) const override {
  22. std::clog << "'read_file'";
  23. for (auto const& arg : args) {
  24. std::clog << ' ' << arg;
  25. }
  26. std::clog << std::endl;
  27. }
  28. };
  29.  
  30. struct write_file : command {
  31.  
  32. virtual void exec(args_type const& args) const override {
  33. std::clog << "'write_file'";
  34. for (auto const& arg : args) {
  35. std::clog << ' ' << arg;
  36. }
  37. std::clog << std::endl;
  38. }
  39. };
  40.  
  41. using command_ptr = std::unique_ptr<command>;
  42. using command_map = std::unordered_map<std::string, command_ptr>;
  43.  
  44.  
  45. int main() {
  46. // ассоциативный массив команд
  47. command_map commandMap;
  48. commandMap["read_file" ] = command_ptr(new read_file);
  49. commandMap["write_file"] = command_ptr(new write_file);
  50.  
  51. for (std::string line; std::getline(std::cin, line); ) {
  52. std::istringstream iss(line);
  53.  
  54. std::string commandName;
  55. iss >> commandName;
  56.  
  57. auto const it = commandMap.find(commandName);
  58. if (it != std::end(commandMap)) {
  59. command::args_type const commandArgs(
  60. std::istream_iterator<std::string>{iss}
  61. , std::istream_iterator<std::string>{});
  62.  
  63. it->second->exec(commandArgs);
  64. } else {
  65. std::cerr << "'" << commandName << "' - unrecognized command" << std::endl;
  66. }
  67. }
  68. }
  69.  
Success #stdin #stdout #stderr 0s 3440KB
stdin
read_file someFile andOption
read someOption
write_file someFile
write
stdout
Standard output is empty
stderr
'read_file' someFile andOption
'read' - unrecognized command
'write_file' someFile
'write' - unrecognized command