后缀表示法的堆栈和弹出帮助。打印错误值,C 程序

Stack and pop help for postfix notation. Printing wrong values, C prog

我的代码接受 1 个命令行参数,它逐个字符地读取命令行并相应地放置堆栈。

命令行参数:“12+”应等于“1+2”的等式

int pop(stack *p);

int main(int argc, char **argv)
{

    stack ph;
    int i, a, b;
    int val = 0;

    if (argc!=2)
    {
            printf("Usage: %s argument\n", argv[0]);
            exit(1);
    }
    else{
            int i;
            int length = strlen(argv[1]);
            int count;
            initializedStack(&ph);

            for(i=0;i<length;i++)
            {
                    if (argv[1][i] == '+'){
                            a = pop(&ph);
                            printf("%d\n", a);
                            b = pop(&ph);
                            printf("%d\n", b);
                            val = a+b;
                            push(&ph,val);
                    }
                    else{
                            push(&ph, argv[1][i]);
                    }
            }
            printf("%d\n", pop(&ph));
    }

    return 0;
}

void initializedStack(stack *p){
    p->top = 0;
}

void push(stack *p, int val){
    p->top++;
    p->items[p->top] = val;
}

int pop(stack *p){
    int y;
    y = p->items[p->top];
    p->items[p->top] = 0;
    (p->top)--;
    return y;
}

我目前在程序的测试阶段,它只包括加法运算。为了测试这个程序,我在 if 语句的添加部分打印语句,最后弹出。 运行 这给了我输出:

50
49
99

当输出应该是:

1
2
3

加法运算好像可以,但不知道50和49是从哪里来的?编写代码以提供准确输出的正确方法是什么?谢谢!

当你这样做时:

push(&ph, argv[1][i]);

您正在推送给定数字的 ASCII 值并且 不是 它的解码数值 [后者相当于 atoi 会 return,如果它可以对单个字符进行操作的话。

这可能不是你想要的,因为稍后你推送 a + b,这是 numeric/binary 个值。

虽然这仅适用于 单个 数字,但快速修复是:

push(&ph, argv[1][i] - '0');

否则,一般来说,您需要 assemble 整个 数字字符串并使用(例如)atoi.[=19 对其进行解码=]

在这种情况下,您需要处理一些空格 12 23 +


这是一个清理版本,使用 strtokatoi 允许更通用的数字。 [请原谅不必要的样式清理]:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    int top;
    int items[100];
} stack;

void
initializedStack(stack *p)
{
    p->top = 0;
}

void
push(stack *p, int val)
{
    p->top++;
    p->items[p->top] = val;
}

int
pop(stack *p)
{
    int y;

    y = p->items[p->top];
    p->items[p->top] = 0;
    (p->top)--;
    return y;
}

int
main(int argc, char **argv)
{
    stack ph;
    int i,
     a,
     b;
    int val = 0;
    char *buf;
    char *token;
    int chr;

    if (argc != 2) {
        printf("Usage: %s argument\n", argv[0]);
        exit(1);
    }

    buf = argv[1];

    initializedStack(&ph);

    while (1) {
        token = strtok(buf," ");
        if (token == NULL)
            break;
        buf = NULL;

        chr = token[0];

        if (strcmp(token,"+") == 0) {
            a = pop(&ph);
            printf("%d\n", a);

            b = pop(&ph);
            printf("%d\n", b);

            val = a + b;
            push(&ph, val);
            continue;
        }

        if ((chr >= '0') && (chr <= '9')) {
            val = atoi(token);
            push(&ph, val);
            continue;
        }
    }

    printf("%d\n", pop(&ph));

    return 0;
}