C:数组中的第一个数字由于未知原因变为 0

标签 c arrays sorting

计划:
这应该是一个简单的反向波兰符号添加程序,请忽略 EOF 中断,它是一个占位符。 输入是 c,始终是一个数字,它会被传输到 x,其中每个下一个数字 c 将添加到数字 x,因此,例如,当我们输入 c 作为 1,2 和 3 时,x 将是 123。 当我们输入“e”时,它会标记一个新数字的开始,整个堆栈被推回后,x将被转移到stack[0]中,x将变为0。当输入“+”发生加法时,最后两个数字将被相加,x 和堆栈中的第一个数字,或者堆栈中的第一个和第二个数字,或者堆栈中的第一个数字将重复自身。

问题:
堆栈数组中的第一个数字将随机变为 0,我看不到我在哪里犯了错误。第一个数字(stack[0])仅在开始时获得零值,再也不会。有时输入“+”时它只会得到一个值。

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

int main()
{
    int stack[16];
    int x;
    int i;
    char c;
    //int c;
    x=0;

    for (i = 0; i < 16; i++)
        {
            stack[i]=0;
        }

    while(1)
    {
        //input character
        scanf("%s", &c);

        if (c == EOF) break;
        //put x to stack
        else if (c == 'e')
            {for (i = 15; i >0; i--)
            {
                stack[i]=stack[i-1];
            }
        stack[0] = x;
        x = 0;
        }
        //reverse polish addition
        else if (c == '+')
            //if x is 0 go immediately to the stack
            {if (x == 0)
                    //if both x and the second number in array are 0 just duplicate the first number
                  if (stack[1] == 0)
                    stack[0] = stack[0] + stack[0];
                    //if only x is 0 add the first number on the second
                  else
                  {
                stack[0]=stack[0]+stack[1];
                //push back the array to fill the gap on the second number
                for (i = 1; i <15; i++)
                {
                    stack[i]=stack[i+1];
                }

            }
            else
            {
                stack[0] = stack[0] + x;
                x = 0;
            }
        }
        else
        {
        x = x * 10 + ((int)c-0x30);
        // putchar(c);
        }
        printf("X=%d\n",x);
        //print stack
        for (i = 0; i < 16; i++)
        {
            printf("%d \t",stack[i]);
        }
        printf("\n");
    }
    return 0;
}

最佳答案

问题 1

scanf("%s", &c); 导致未定义的行为。使用 scanf("%c", &c);

问题2

使用 scanf 时,

c 永远不会等于 EOF。因此,下面的行是没有用的。

    if (c == EOF) break;
<小时/>

下面将解决这两个问题。

// Use " %c" instead of "%c" to skip leading whitespace characters.
while ( scanf(" %c", &c) == 1 )
{
}

关于C:数组中的第一个数字由于未知原因变为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49804015/

相关文章:

php - 检查键是否是数组中的最后一个元素?

c - 简单的C程序错误

arrays - 在swift中过滤元素出现次数最多的数组

java - 如何在 hibernate 中使用条件对列表进行排序

list - 当对象是动态的时,如何在 Scala 中对列表进行排序?

Javascript 根据类对 DIV 进行排序

android - 如何在 android 中查看 native 编译的 C 程序的堆栈跟踪?

c - 初始化结构变量时出错?

c - MISRA 是否检查数组索引是否越界?

c - 检测宽屏幕纵横比