diff --git a/2021-oop1/ku/stream-05-19-2021/input_parsing.cpp b/2021-oop1/ku/stream-05-19-2021/input_parsing.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7f16b33f8621c5c035ff6ba4798eae139f960420 --- /dev/null +++ b/2021-oop1/ku/stream-05-19-2021/input_parsing.cpp @@ -0,0 +1,89 @@ +#include <iostream> +#include <algorithm> + +// VALID COMMANDS: +// "quit" +// "set x" + + +enum Command {QUIT, SET }; + +std::string readInput() +{ + std::string input_string; + std::cout << "> "; + std::getline(std::cin, input_string); + if(input_string.length() > 10) + throw std::length_error("[ERROR] Input too long"); + if(input_string.length() < 4) + throw std::length_error("[ERROR] Input too short"); + + std::transform(input_string.begin(), input_string.end(), input_string.begin(),[](unsigned char c){ return std::tolower(c); }); + return input_string; +} + +size_t validateAndGetNrOfWords(std::string& input) +{ + size_t nr_of_words = std::count(input.cbegin(), input.cend(), ' ') + 1; + if(nr_of_words != 1 && nr_of_words != 2) + throw std::out_of_range("[ERROR] too many words"); + return nr_of_words; +} + +Command getValidCommand(std::string& input) +{ + size_t nr_of_words = validateAndGetNrOfWords(input); + if(nr_of_words == 1) + { + if(input == "quit") + return Command::QUIT; + else + throw std::invalid_argument("[ERROR] invalid command with one word"); + } + else + { + if(input == "set x") + return Command::SET; + else + throw std::invalid_argument("[ERROR] invalid command with two words"); + } +} + +Command getCommand() +{ + while(true) + { + try + { + std::string input = readInput(); + Command current_command = getValidCommand(input); + return current_command; + } + catch(std::length_error& e) + { + std::cout << e.what() << std::endl; + } + catch(std::out_of_range& e) + { + std::cout << e.what() << std::endl; + } + catch(std::invalid_argument& e) + { + std::cout << e.what() << std::endl; + } + } +} + + +int main() +{ + std::cout << "Insane OOP Game - enter set x or quit" << std::endl; + Command current_command = SET; + while(current_command != QUIT) + { + current_command = getCommand(); + std::cout << (current_command == SET ? "SET X COMMAND" : "QUIT COMMAND") << std::endl; + } + + return 0; +}