C中的RPN计算器

时间:2016-07-22 06:00:45

标签: c calculator rpn

有人可以解释为什么我在myString上使用strok()后会一直乱哄哄吗?我输出的图片位于底部。我尝试将myString中的每个元素初始化为NULL字符,但我的代码仍无效:(

预期产出:

enter image description here

我的输出:

enter image description here

int main()
{
    int i;
    char myString[60];
    char *token;
    float result;
    float x;
    float y;
    struct Stack myStack;
    StackInit(&myStack);


    BOARD_Init();

    printf("\nWelcome to my RPN calculator.\n");
    printf("Enter floats and + - / * in RPN format: \n >");

    for (i = 0; i < sizeof (myString); i++) {
        myString[i] = '\0';
    }

    fgets(myString, sizeof (myString), stdin);



    token = strtok(myString, " ");
    while (token != NULL) {
        printf("%f\n", atof(token));
        token = strtok(NULL, " ");

        if (atof(token) != 0) {
            StackPush(&myStack, atof(token));
        } else if (*token == '+') { // if token is addition
            StackPop(&myStack, &y);
            StackPop(&myStack, &x);
            result = x + y;
            StackPush(&myStack, result);

        } else if (*token == '-') { // if token is subtraction
            StackPop(&myStack, &y);
            StackPop(&myStack, &x);
            result = x - y;
            StackPush(&myStack, result);
        } else if (*token == '*') { // if token is multiplication
            StackPop(&myStack, &y);
            StackPop(&myStack, &x);
            result = x * y;
            StackPush(&myStack, result);
        } else if (*token == '/') { // if token is division
            StackPop(&myStack, &y);
            StackPop(&myStack, &x);
            result = x / y;
            StackPush(&myStack, result);
        }

    }




while (1);

}

1 个答案:

答案 0 :(得分:0)

正如@BLUEPIXY在评论中指出的那样,您的代码存在问题:

token = strtok(myString, " ");   // Here you get the first sub string
while (token != NULL) {
    printf("%f\n", atof(token));
    token = strtok(NULL, " ");   // Here you get the second sub string
                                 // and throw away the first substring
                                 // So all the code below is never executed
                                 // for the first substring.
                                 // In other words: You never push the first
                                 // float to the stack

    if (atof(token) != 0) {
        StackPush(&myStack, atof(token));

你应该做的是将token = strtok(NULL, " ");移到循环的末尾:

while (token != NULL) {
    printf("%f\n", atof(token));
    // Not here............. token = strtok(NULL, " ");

    if (atof(token) != 0) {
        StackPush(&myStack, atof(token));
    } else if (*token == '+') { // if token is addition
    //...
    //...
    }

    token = strtok(NULL, " ");    // but here
}