简体   繁体   English

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

[英]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.那么问题出在while循环中。

Why my while loop condition not working ?为什么我的 while 循环条件不起作用? checking temp isn't equal to NULL检查 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;
}

Thanks in advance提前致谢

Why you are re-declare char ch inside the loop ?为什么要在loop重新声明char ch

Remove char ch inside loop and fix your problem.删除循环内的char ch并解决您的问题。 Like,喜欢,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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