newBike newBike - 13 days ago 9
C Question

Parse simple math equation with 2 operands and 1 operator in the middle

I only need to handle the following equations.

9-8

5222/12

322*445

7878+7

However, when I enter

8+9
as the inpurt.
The console only shows
8.000000+

It seems not handling the last operand.

I guest the I didn't have this branch correctly
else if(isOperator(*endTemp))


Any idea? or direction?

static double getUserInputValues() {
double values[NUM_OF_USER_INPUT_VALUES];
while (1) {
errno = 0;
char temp[257];
char operator;
fgets(temp, 256, stdin);
char *str = strtok(temp, " ");

int cnt = 0;
while (str != NULL && cnt < NUM_OF_USER_INPUT_VALUES) {
char *endTemp;
double val = strtod(str, &endTemp);
printf("%f", val);
if (*endTemp == 0 || *endTemp == '\n') {
values[cnt] = val;
cnt++;
str = strtok(NULL, " ");
} else if(isOperator(*endTemp)){
operator = *endTemp;
printf("%c", operator);
str = strtok(NULL, " ");
}
else {
errno = 1;
break;
}
}
}
return getReturnValue(values, operator);;
}


static bool isOperator(char ch){
switch(ch){
case '+':
return 1;
case '-':
return 1;
case '*':
return 1;
case '/':
return 1;
default:
return 0;
}
}

Answer

Before I begin, I highly suggest that you learn how to use a debugger, since these kinds of things are exactly the reason why they exist. Knowing how to debug a problem effectively, is an indispensable tool in a programmer's toolkit.

Anyway, strtod will try to parse a floating point number from a string, placing the rest of what it did not parse in the pointer given in the second argument.

strtok will break a string into tokens. In your case, you are delimiting using a space, and so the first token you will get from the input "8+9", will be "8+9", as there are no spaces in this input.

A call to strtod will then parse out the 8 from this token, storing the rest of the string "+9" in endTemp.

You are only extracting the operator in your code, after which you proceed to discard the remaining contents and take the next token.

operator = *endTemp; // endTemp == "+9" at this point
                     // so *endTemp == '+'.
printf("%c", operator);
str = strtok(NULL, " "); // discard current token (9 is not handled).

As you can see, you are not handling the remaining number.

A simple fix would be the following:

operator = *endTemp; // endTemp == "+9" at this point
                     // so *endTemp == '+'.
printf("%c", operator);
str = endTemp + 1;   // str == "9" now.
Comments