程序自动终止,无需等待我的回复。为什么?

时间:2016-06-18 08:15:18

标签: 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;
}

2 个答案:

答案 0 :(得分:4)

请更改

scanf("%c", &ans);

scanf(" %c", &ans);

注意添加的空间,它消耗了前一次输入后留在输入缓冲区中的newline

请注意,某些格式说明符(如%d%s)会自动使用任何前导空格,并在缓冲区中留下不适合该格式的下一个字符。如果您的%dnewline

然而,格式%c从输入缓冲区收集下一个字符,无论它是什么,并且前导空格阻止了它。

答案 1 :(得分:1)

除了在格式字符串中添加空格以使用上面提到的换行符之外,检查scanf返回值也是一个很好的做法,因为它可能无法输入整数值并仍然pushm的旧值放入堆栈。

int main(void)
{
    int m;
    char ans;
    int ret;
    do
    {
        printf("\nEnter the no. to insert in stack: \n");
        ret = scanf("%d", &m);
        if (ret != 1) {
            printf("invalid input\n");
            continue;
        }
        push(m);

        printf("\nDo you want to enter more data???\n");
        ret = scanf(" %c", &ans);
        if (ret != 1) {
            printf("invalid input\n");
            continue;
        }
    } while(ans == 'y' || ans == 'Y');
}
相关问题