【发布时间】:2021-02-08 02:33:18
【问题描述】:
我正在尝试一个简单的程序,该程序将创建一个链接列表并在之后显示元素。
在这个程序中,我使用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",i,ptr->num);
return 0;
}
现在上面的程序在进入y时将10'\n'存储在ch中,结果do while循环被终止;
但是当我使用 cin 而不是 scanf() 时,上述程序运行正常。
所以请任何人帮我解释为什么scanf() 无法将y 存储在ch 中?
【问题讨论】:
-
非常感谢@user3121023;你能解释一下为什么
scanf()不给空间就不能工作吗? -
附带说明:在不检查返回值的情况下使用
scanf是不安全的。有关详细信息,请参阅此页面:A beginners' guide away from scanf()