带空格分隔符的strtok()函数

时间:2014-04-19 15:25:12

标签: c strtok rpn

我试图用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()函数中使用逗号或fullstop作为分隔符时,它可以工作,但是有空格,它只能读取第一个标记。

任何帮助?

由于

1 个答案:

答案 0 :(得分:3)

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

scanf("%s", expression);

只要scanf看到一个空格,一个TAB或任何其他分隔符,它就会停止读取,然后将该字返回到该空格。这就是为什么它在你使用非空白分隔符时有效。

替换为fgets以解决问题:

fgets(expression, 100, stdin);