简体   繁体   中英

why my while loop condition not working?

This program asks for number irrespective of what character you enter. Then the problem is in the while loop.

Why my while loop condition not working ? checking temp isn't equal to 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;
}

Thanks in advance

Why you are re-declare char ch inside the loop ?

Remove char ch inside loop and fix your problem. Like,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM