Files
Calculator/input_resolver.cpp

91 lines
1.7 KiB
C++

#include "input_resolver.h"
#include <string>
#include <iostream>
#include <sstream>
#define delimiter " "
struct ValidationResult
{
bool ok()
{
return isItOk;
}
char incorrect_token()
{
return in_t;
}
int next_arg()
{
return nextArg;
}
bool isItOk;
char in_t;
int nextArg;
};
ValidationResult validate_token(const std::string &token)
{
static const std::string allowedTokens{"+-*/%$qp"};
char incorrectToken;
size_t digitpos = -1, counter = 0;
for (const char c: token)
{
if (allowedTokens.find(c) == allowedTokens.npos && !isdigit(c) && !isspace(c))
return {false, c};
if (digitpos == -1 && isdigit(c))
digitpos = counter;
counter++;
}
if (digitpos == -1)
return {true, token[0], 0};
int next = stoi(token.substr(digitpos));
return {true, token[0], next};
}
Command resolveCommand()
{
std::string st;
getline(std::cin, st);
std::string token = st.substr(0, st.find(delimiter));
auto validation_result = validate_token(token);
if (!validation_result.ok())
{
std::ostringstream os;
os << "invalid token "<< validation_result.incorrect_token();
throw std::runtime_error{os.str()};
}
bool shouldQuit = token.find("q") != token.npos;
bool shouldPrint = token.find("p") != token.npos;
char operation = 0;
for (const char c: token)
{
static const std::string operators {"+-*/%$"};
if(operators.find(c) != operators.npos)
{
operation = c;
}
}
if (operation == 0)
{
operation = '+';
}
return {shouldQuit, operation, validation_result.next_arg(), shouldPrint};
}