为什么我的while循环条件不起作用?

时间:2017-02-08 08:49:06

标签: c while-loop do-while

无论您输入什么字符,此程序都会询问号码。然后问题出现在while循环中。

为什么我的while循环条件不起作用?检查temp不等于NULL

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

typedef struct node
{
    int num;
    struct node *ptr;
} nod;
nod *head = NULL;

void insert()
{
    int n;
    nod *temp = (struct node*) malloc(sizeof(struct node));
    printf("Enter nnumber \n");
    scanf("%d", &n);
    temp->num = n;
    temp->ptr = NULL;
    if (head == NULL)
    {
        head = temp;
    }
    else
    {
        temp->ptr = head;
        head = temp;
    }
}

void display()
{
    nod* temp;
    temp = head;
    while (temp != NULL)
    {
        printf(" --> %d", temp->num);
        temp = temp->ptr;
    }
}

int main()
{
    char ch;
    do
    {
        insert();
        display();
        char ch;
        printf("\n enter more data ? (y/n)");
        scanf("\n %c", &ch);
    }
    while (ch != 'n');
    return 0;
}

提前致谢

1 个答案:

答案 0 :(得分:2)

为什么您在char ch重新声明 loop

删除内部循环中的char ch并修复问题。像,

int main()
{
    char ch;
    do
    {
        insert();
        display();
        printf("enter more data ? (y/n)\n");
        scanf(" %c", &ch);
    }
    while (ch != 'n');    
    return 0;
}