问题描述
我正在尝试一个简单的程序,该程序将创建一个链接列表并在以后显示元素。
在此程序中,我使用char
变量ch
存储是/否,以便在链接列表中输入更多节点。
考虑以下程序:
#include<stdio.h>
#include<malloc.h>
struct node
{
int num;
struct node *next;
};
struct node *start=NULL;
int main()
{
struct node *ptr,*new_node;
int data,i;
char ch;
do
{
printf("Enter node value:");
scanf("%d",&data);
new_node=(struct node *)malloc(sizeof(struct node));
new_node->num=data;
if(start==NULL)
{
new_node->next=NULL;
start=new_node;
}
else
{
ptr=start;
while(ptr->next!=NULL)
ptr=ptr->next;
ptr->next=new_node;
new_node->next=NULL;
}
printf("Want to enter more nodes (Y/N)?");
scanf("%c",&ch);
}while((ch=='y')||(ch=='Y'));
printf("\nThe entered elements in the linked lists is as follows:\n");
ptr=start;
i=1;
while(ptr->next!=NULL)
{
printf("Node %d is %d\n",i,ptr->num);
i++;
ptr=ptr->next;
}
printf("Node %d is %d\n",ptr->num);
return 0;
}
现在,上述程序在输入10'\n'
时将ch
存储在y
中,结果do while
循环终止;
但是当我使用cin
而不是scanf()
时,上述程序可以正常工作。
因此,请任何人帮助我解释为什么scanf()
无法在y
中存储ch
吗?
解决方法
我不确定原因,只是在您的scanf("%c",&ch)
中放一个空格,它将开始起作用。
只需将其更改为scanf(" %c",&ch)
您可以检查某个地方是否有原因,然后将其注释掉,但是现在这将对您有所帮助。只是一个猜测,可能是ch
读取的新字符是换行符,该行本身终止了它。