c代码的一些问题

c代码的一些问题,c,C,当我在菜单中选择push时,我输入一些数字值,然后程序工作正常,但当我输入一些字母值时,程序从不停止,我的错误在哪里? 我是c语言的初学者,也许有人能帮我解决这个问题。 我有以下代码: #include <stdio.h> #include <curses.h> int a[15], top = -1; void push (int value) { if (top == 14) { printf("Stack is full");

当我在菜单中选择push时,我输入一些数字值,然后程序工作正常,但当我输入一些字母值时,程序从不停止,我的错误在哪里? 我是c语言的初学者,也许有人能帮我解决这个问题。 我有以下代码:

#include <stdio.h>
#include <curses.h>

int a[15], top = -1;

void push (int value)
{
    if (top == 14)
    {
        printf("Stack is full");
    }
    else{
        top = top + 1;
        a[top] = value;
    }
}

void pop()
{
    if (top == -1)
    {
        printf("Stack is empty");
    }
    else
    {
        top = top - 1;
    }
}


void display()
{
    int i;
    if (top == -1)
    {
        printf("\n Nothing to display");
    }
    else
    {
        printf("\nArray is:\n");
        for (i=0; i<=top; i++)
        {
            printf("%d\n", a[i]);
        }
    }
}


int main()
{
    int choice, value;
    do{
        printf("\n1.Push :");
        printf("\n2.POP :");
        printf("\n3.Display :");
        printf("\n4.Exit :");
        printf("\nEnter your Choice:");
        scanf("%d", &choice);

        if(choice == 1)
        {
            printf("\nEnter Value to be inserted: ");
            scanf("%d", &value);
            push(value);
        }

        if(choice == 2)
        {
            pop();
        }

        if (choice == 3)
        {
            display();
        }

    }
    while (choice !=4);
    getch();

    return 0;
}
#包括
#包括
INTA[15],top=-1;
无效推送(int值)
{
如果(顶部==14)
{
printf(“堆栈已满”);
}
否则{
顶部=顶部+1;
a[顶部]=数值;
}
}
void pop()
{
如果(顶部==-1)
{
printf(“堆栈为空”);
}
其他的
{
top=top-1;
}
}
无效显示()
{
int i;
如果(顶部==-1)
{
printf(“\n无需显示”);
}
其他的
{
printf(“\n数组为:\n”);

对于(i=0;i您需要更改两件事才能使代码正常工作

char a[15];
char value;

另外,您还需要向函数传递一个字符,而不是整数。

您的推送函数采用
int
值,为什么要在此行中推送
char
@miteshant
void push(int值)
我从int改为char,但问题是一样的。在这一部分中,我需要同时输入字母和数字,所以我需要char,write?您需要像
(char)input
一样将输入转换为char,并使用char作为push参数typeunrelated,但由于每个
选项
都是互斥的,因此如果(选项==1),您应该将其改为
{…}elseif(choice==2){…}elseif(choice==3){…}
。当选项只有一个(或没有)时,每次都根据这些条件检查选项是没有意义的。当存在非法输入时,有必要清除输入缓冲区。例如
如果(0==scanf(“%d”,&var)){while(getchar()!='\n');输入_NG=1;}