Code:
// 1 = add 2 = subtract 3 = mlutiply 4 = divide
int findOperator(int *operation, int *num1, int *num2, char *c)
{
const char add = '+';
const char subtract = '-';
const char multiply = 'x';
const char divide = '/';
char *tok1, *tok2, *saveptr;
char str1[1+strlen(c)];
strcpy(str1, c);
if (strrchr(c, add) )
{
tok1 = strtok_r(c, "+", &saveptr);
tok2 = strtok_r(NULL, "+", &saveptr);
if ( tok2 == NULL)
{
return -1;
}
else
{
tok1 = strtok_r(str1, "+", &saveptr);
tok2 = strtok_r(NULL, "+", &saveptr);
*num1 = atoll(tok1);
*num2 = atoll(tok2);
*operation = 1;
return 1;
}
}
if (strrchr(c, subtract) )
{
tok1 = strtok_r(c, "-", &saveptr);
tok2 = strtok_r(NULL, "-", &saveptr);
if ( tok2 == NULL)
{
return -1;
}
else
{
tok1 = strtok_r(str1, "-", &saveptr);
tok2 = strtok_r(NULL, "-", &saveptr);
*num1 = atoll(tok1);
*num2 = atoll(tok2);
*operation = 2;
return 1;
}
}
if (strrchr(c, multiply) )
{
tok1 = strtok_r(c, "x", &saveptr);
tok2 = strtok_r(NULL, "x", &saveptr);
if ( tok2 == NULL)
{
return -1;
}
else
{
tok1 = strtok_r(str1, "x", &saveptr);
tok2 = strtok_r(NULL, "x", &saveptr);
*num1 = atoll(tok1);
*num2 = atoll(tok2);
*operation = 3;
return 1;
}
}
if (strrchr(c, divide) )
{
tok1 = strtok_r(c, "/", &saveptr);
tok2 = strtok_r(NULL, "/", &saveptr);
if ( tok2 == NULL)
{
return -1;
}
else
{
tok1 = strtok_r(str1, "/", &saveptr);
tok2 = strtok_r(NULL, "/", &saveptr);
*num1 = atoll(tok1);
*num2 = atoll(tok2);
*operation = 4;
return 1;
}
}
return -1;
}
my first thought for what you are doing is putting the numbers in an char array then using that and looping around it with your input to check it until you find a match to a one number format if not then return your error code.