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

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

提前致谢

最佳答案

为什么要在循环重新声明 char ch

删除循环内的char ch并解决您的问题。就像,

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

关于c - 为什么我的 while 循环条件不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42108460/

相关文章:

c - 地址的打印输出长度不同

java while 循环

javascript - 我的 do while 循环陷入无限循环

java - 向现有的 java 程序添加循环?

C++ Do-while循环停止

c++ - 将 C++ 代码转换为 C 时程序崩溃

c - GLib 在 XCode 中的使用

c - 在C中如何使用printf输出球坐标转换为笛卡尔坐标的值?

c - 如何在 while 循环中转换此 goto 循环?

java - 比较java中的char变量