【问题标题】:while() loop not working as expected. What could be the reason?while() 循环未按预期工作。可能是什么原因?
【发布时间】:2014-06-20 19:53:35
【问题描述】:

我已经开始用C编写链表了。我的代码如下:

#include<stdio.h>
#include<malloc.h>
struct node
{
    int data;
    struct node *next;       

};

struct node * create(struct node *);
display(struct node *);

int main()
{  
    struct node *head=NULL;

    head = create(head);
    display(head);

    getch();
    return 0;

}

struct node * create(struct node *Head)
{
   struct node *temp;
   char ch='y';
   int i=1;
   while(ch=='y')
   {    
        temp=malloc(sizeof(struct node));
        temp->data=i*10;
        temp->next=Head;
        Head=temp;

        printf("\nAdded node : %d",Head->data);

        printf("\nContinue to add more nodes ?   :  ");
        scanf("%c",&ch);      
   }


   return Head;           

}


display(struct node *Head)
{
   while(Head!=NULL)
   { printf("%d\t%d\n",Head->data,Head->next);
         Head=Head->next;
   }

}

我面临的问题是在进入函数“create”并只创建一个节点后,我的程序跳转回main,然后跳转到“display”函数,然后又跳转回函数“create”在询问我是否要继续的行。此时,当我输入“y”时,程序就退出了! 为什么会有这种行为?? 有人请解释一下控制是如何流动的以及为什么我的程序会出问题!!!

【问题讨论】:

    标签: c function linked-list singly-linked-list control-flow


    【解决方案1】:

    原因:

    发生这种情况是因为当您输入'y' 然后按回车键时,换行符'\n' 会被缓冲,并将在scanf() 的下一次迭代中读取。这将导致while(ch=='y') 评估为false(现在是ch == '\n'),从而中断循环。

    通常scanf() 会在达到预期值之前跳过空格和换行符。但是,当您使用字符格式 %c 时,这不会发生,因为换行符和空格也是有效字符。


    如何解决:

    您可以使用scanf(" %c",&amp;ch); 修复它。 %c 之前的空格将在实际读取值之前跳过缓冲区中发现的任何前导退格或换行符。

    【讨论】:

    • 行得通!但还有一个小故障......,在每个节点中,我都插入到它的数据字段中:i * 10,其中 i 被初始化为 1。但每次 10 被插入到每个节点中。为什么??
    • 嗯...那是因为1*10 == 10。这就是你所做的一切。如果您想要另一个值,则需要更改i 的值。在每次迭代之后创建一个i++ 就可以了。
    • 当我将 'ch' 的数据类型从 char 更改为 int 时,将 'ch' 初始化为 1,并将条件更改为:while(ch==1),我不面对' \n' 得到缓冲问题。为什么?
    • 问题已解决.. 即使我不更改数据类型并且一切都保持不变,除了在我输入 ch 值的语句中,而不是在 scanf 中使用 %c,我使用%d,不再有缓冲问题。
    • 是的。这里指的是第二段“理由”部分的答案。 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 2020-11-05
    • 1970-01-01
    • 2019-10-29
    • 1970-01-01
    • 1970-01-01
    • 2022-11-04
    相关资源
    最近更新 更多