You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
#include "operationHandler.h"
#include <stdbool.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
// checking integer input as operation id
bool checkOperationInput(int input) { switch (input) { case 4: case 3: case 2: case 1: return true; } return false; }
// full input process
int* evaluateInput(char* input, int operation) { // check if formatting is correct
if(!containsTwoNumbers(input)) return NULL; int firstNumber = extractFirstNumber(input); // origin string "input" has been edited
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; }
// formatting check of string
bool containsTwoNumbers(const char* str) { int numbersCount = 0; bool hasSpace = false; bool isInNumber = false;
for (int i = 0; str[i] != '\0'; i++) { if (isdigit(str[i])) { if (!isInNumber) { isInNumber = true; numbersCount++; } } else if (str[i] == ' ' && isInNumber) { hasSpace = true; isInNumber = false; } else if (str[i] == ' ' && !isInNumber) { hasSpace = false; } else { hasSpace = false; isInNumber = false; } } return (numbersCount == 2 && hasSpace); }
// extracting of first number and removing from string
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; }
void outputInteger(int output) { outputTemplate(); printf("Result: %d", output); }
void outputLong(long output) { outputTemplate(); printf("Result: %ld", output); }
void outputDouble(double output) { outputTemplate(); printf("Result: %lf", output); }
void outputFloat(float output) { outputTemplate(); printf("Result: %f", output); }
void outputTemplate() { printf("###############################\n-> Calculator\n#################################"); }
|