diff --git a/src/operationHandler.c b/src/operationHandler.c index ef41efb..616b627 100644 --- a/src/operationHandler.c +++ b/src/operationHandler.c @@ -2,6 +2,7 @@ #include #include #include +#include bool checkOperationInput(int input) { switch (input) { @@ -11,6 +12,28 @@ bool checkOperationInput(int input) { return false; } +int* evaluateInput(char* input, int operation) { + if(!containsTwoNumbers(input)) return NULL; + int firstNumber = extractFirstNumber(input); + int secondNumber = atoi(input); + int* result = malloc(sizeof(int)); + switch (operation) { + case 1: + *result = firstNumber + secondNumber; + break; + case 2: + *result = firstNumber - secondNumber; + break; + case 3: + *result = firstNumber * secondNumber; + break; + case 4: + *result = firstNumber / secondNumber; + break; + } + return result; +} + bool containsTwoNumbers(const char* str) { int numbersCount = 0; bool hasSpace = false; @@ -33,4 +56,36 @@ bool containsTwoNumbers(const char* str) { } } return (numbersCount == 2 && hasSpace); +} + +int extractFirstNumber(char* str) { + int number = 0; + bool isInNumber = false; + int endIndex = 0; + + for (int i = 0; str[i] != '\0'; i++) { + if (isdigit(str[i])) { + if (!isInNumber) { + isInNumber = true; + number = str[i] - '0'; + } else { + number = number * 10 + (str[i] - '0'); + } + } else if (str[i] == ' ' && isInNumber) { + endIndex = i; + break; + } else { + isInNumber = false; + } + } + + int index = 0; + char temp[strlen(str)-endIndex+1]; + for(int i = endIndex+1; i < strlen(str); i++) { + temp[index++] = str[i]; + } + temp[index] = '\0'; + strcpy(str, temp); + + return number; } \ No newline at end of file diff --git a/src/operationHandler.h b/src/operationHandler.h index cb083e2..58ca89a 100644 --- a/src/operationHandler.h +++ b/src/operationHandler.h @@ -4,6 +4,10 @@ bool checkOperationInput(int); +int* evaluateInput(char*, int); + bool containsTwoNumbers(const char*); +int extractFirstNumber(char*); + #endif //THEADMIRALS_OPERATIONHANDLER_H