c - 程序自动终止,无需等待我的响应。为什么?

标签 c stack do-while

<分区>

我正在编写一个将数字输入堆栈的程序,do-while 循环自动完成,无需等待我的响应。因此只获取并显示了一个数据。

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

struct node
{
    int data;
    struct node *next;
};
typedef struct node NODE;

NODE *top = NULL;

void push(int x)
{
    NODE *p;

    p = (NODE*)malloc(sizeof(NODE));
    p->data = x;
    p->next = top;
    top = p;
}

void display(void)
{
    NODE *t;

    t = top;
    if(t == NULL)
    {
        printf("\nstack is empty");
    }
    else
    {
        while(t != NULL)
        {
            printf("%d ", t->data);
            t = t->next;
        }
    }
}

int main(void)
{
    int m;
    char ans;

    do
    {
        printf("\nEnter the no. to insert in stack: \n");
        scanf("%d", &m);
        push(m);

        printf("\nDo you want to enter more data???\n");
        scanf("%c", &ans);
    } while(ans == 'y' || ans == 'Y'); // here after entering a value for variable 'm', the program terminates displaying the stack with one element.

    display();
    return 0;
}

最佳答案

请更改

scanf("%c", &ans);

scanf(" %c", &ans);

注意添加的空间,它占用了 换行符,它在上一次输入后留在输入缓冲区中。

请注意,一些格式说明符,例如 %d%s 会自动消耗所有前导空格,并在缓冲区中留下不适合该格式的下一个字符。对于您的 %d,这是一个 换行符

然而,格式 %c 会从输入缓冲区中收集下一个字符,而不管它是什么,而前导空格会阻止这种情况。

关于c - 程序自动终止,无需等待我的响应。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37894817/

相关文章:

C动态分配指向主函数的指针

algorithm - 其中的递归和内存使用

c - 在函数中切换 do..while 循环的最佳方法?

c++ - 为什么 while 循环会无限重复?

c - 退出 do while 循环 C 时出错

c++ - 如何构造清理代码?

c - C语言中的 ':-!!'是什么?

c - 检查有效 Unix FTP 命令的程序(不工作)

c++ - 哪种数据结构最适合 C++ 中的基本堆栈和队列?

C - 在 while 中获取 char 并压入堆栈