I am trying to make a C string calculator. This means that I have a string with numbers and a delimiter in the middle. the delimiter can be of any size as long as it isn't a number. Also, if the value of a specific number is between 1001 and 1111 it cannot be used and will be ignored (set to zero). The difficulty of this assignment is to make the delimiting/splitting string part without strtok
. I am getting all sorts of wrong outputs and I have no idea what I am doing wrong, yet I feel like I am oversighting something or doing something incredibly stupid. The code also freezes my unit tests, so I cant even test what is going wrong.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdbool.h>
void ValidateInput(int *x) {
if (*x >= 1001 && *x <= 1111) {
x = 0;
}
}
int test(char *numbers, int numbers_length, int *result) {
char cnum1[numbers_length];
char cnum2[numbers_length];
strcpy(cnum1, "");
strcpy(cnum2, "");
bool x = false;
size_t i = 0;
while (numbers[i] != '\0') {
char c = numbers[i];
if (isdigit(c)) {
if (x) {
strcat(cnum2, &c);
}
if (!x) {
strcat(cnum1, &c);
}
}
if (!isdigit(c)) {
x = true;
}
i++;
}
int num1;
num1 = atoi(cnum1);
int num2 = atoi(cnum2);
ValidateInput(&num1);
ValidateInput(&num2);
printf("%d\n", num1);
printf("%d\n", num2);
return num1 + num2;
}
int main() {
int sum;
char numbers[] = "100,10";
int length = strlen(numbers);
test(numbers, length, &sum);
return -1;
}