Question

im trying to implement an RPN calculator using C. The following is the code:

    float rpn(void) {
    float ans = 0;
    int top = -1;
    float stack[50];
    char expression[100];
    char *token;
    float newnumber;
    float operand1, operand2;
    int i;
    printf("Enter RPN statement here: \n");
    scanf("%s", expression);

    /* get the first token */
    token = strtok(expression, " ");

    /* walk through other tokens */
    while (token != NULL) {
        if (isdigit(*token)) {
            newnumber = atof(token);
            push(stack, &top, newnumber);
        } else {
            if (top < 1) {
                printf("Error: Not enough operands to perform the operation!\n");
                return ans;
            } else {
                operand1 = pop(stack, &top);
                operand2 = pop(stack, &top);
                newnumber = evaluate(token, operand1, operand2);
                push(stack, &top, newnumber);
                ans = newnumber;
            }
        }
        token = strtok(NULL, " ");

        printf("\nCurrent stack is: \n");
        for (i = 0; i <= top; i++) {
            printf("%f\n", stack[i]);
        }
        printf("\n");
    }
    return ans;
}


    float pop(float* stack, int* top) {
    float ans;
    ans = stack[*top];
    (*top)--;
    return ans;
}

int push(float* stack, int* top, float n) {
    (*top)++;
    stack[*top] = n;
    return 0;
}

float evaluate(char* operator, float x, float y) {
    float ans;
    if (strcmp(operator, "+") == 0) {
        ans = x + y;
    }
    if (strcmp(operator, "-") == 0) {
        ans = x - y;
    }
    if (strcmp(operator, "*") == 0) {
        ans = x * y;
    }
    if (strcmp(operator, "/") == 0) {
        ans = x / y;
    }
    return ans;
}

The problem is that, when using a comma or a fullstop as delimeters in the strtok() function, it works but with space, it only reads up to the first token.

Any help?

Thanks

Was it helpful?

Solution

It's not strtok that reads to the first space, it's scanf:

scanf("%s", expression);

As soon as scanf sees a space, a TAB, or any other delimiter, it stops reading, and returns the word up to the space. That is why it works when you use a non-blank delimiter.

Replace with fgets to fix the problem:

fgets(expression, 100, stdin);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top