1

我正在尝试使用 C 实现 RPN 计算器。以下是代码:

    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;
}

问题是,当在 strtok() 函数中使用逗号或句号作为分隔符时,它可以工作,但使用空格时,它只能读取第一个标记。

有什么帮助吗?

谢谢

4

1 回答 1

3

不是strtok读取到第一个空格,而是scanf

scanf("%s", expression);

一旦scanf看到空格、TAB 或任何其他分隔符,它就会停止读取,并将单词返回到空格。这就是为什么当您使用非空白分隔符时它起作用的原因。

替换fgets为解决问题:

fgets(expression, 100, stdin);
于 2014-04-19T15:27:16.960 回答