Browse Source

Added operation handler method extracting two numbers of input

remotes/origin/develop
Eric Bagus 11 months ago
parent
commit
d36313dcdc
  1. 55
      src/operationHandler.c
  2. 4
      src/operationHandler.h

55
src/operationHandler.c

@ -2,6 +2,7 @@
#include <stdbool.h> #include <stdbool.h>
#include <ctype.h> #include <ctype.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h>
bool checkOperationInput(int input) { bool checkOperationInput(int input) {
switch (input) { switch (input) {
@ -11,6 +12,28 @@ bool checkOperationInput(int input) {
return false; 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) { bool containsTwoNumbers(const char* str) {
int numbersCount = 0; int numbersCount = 0;
bool hasSpace = false; bool hasSpace = false;
@ -34,3 +57,35 @@ bool containsTwoNumbers(const char* str) {
} }
return (numbersCount == 2 && hasSpace); 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;
}

4
src/operationHandler.h

@ -4,6 +4,10 @@
bool checkOperationInput(int); bool checkOperationInput(int);
int* evaluateInput(char*, int);
bool containsTwoNumbers(const char*); bool containsTwoNumbers(const char*);
int extractFirstNumber(char*);
#endif //THEADMIRALS_OPERATIONHANDLER_H #endif //THEADMIRALS_OPERATIONHANDLER_H
Loading…
Cancel
Save