Skip to content
Snippets Groups Projects
Commit 5600e939 authored by Alexander Steinmaurer's avatar Alexander Steinmaurer
Browse files
parents 04a640c8 e17b59a2
No related branches found
No related tags found
No related merge requests found
#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;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment