scanf 的字符变量存储问题
character variable storing issue with scanf
我正在尝试一个简单的程序,它将创建一个链表并随后显示元素。
在这个程序中,我使用 char
变量 ch
来存储 yes/no 以在链表中输入更多节点。
考虑以下程序:
#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()
无法在 ch
中存储 y
?
我不确定原因,但只需在您的 scanf("%c",&ch)
中输入 space,它就会开始工作。
只需将其更改为 scanf(" %c",&ch)
您可以检查是否有某处原因并将其注释掉,但现在这会对您有所帮助。只是猜测可能是 ch
读取的新字符是新行,它本身在那里终止。
我正在尝试一个简单的程序,它将创建一个链表并随后显示元素。
在这个程序中,我使用 char
变量 ch
来存储 yes/no 以在链表中输入更多节点。
考虑以下程序:
#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()
无法在 ch
中存储 y
?
我不确定原因,但只需在您的 scanf("%c",&ch)
中输入 space,它就会开始工作。
只需将其更改为 scanf(" %c",&ch)
您可以检查是否有某处原因并将其注释掉,但现在这会对您有所帮助。只是猜测可能是 ch
读取的新字符是新行,它本身在那里终止。