scanf的字符变量存储问题

问题描述

我正在尝试一个简单的程序,该程序将创建一个链接列表并在以后显示元素。 在此程序中,我使用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读取的新字符是换行符,该行本身终止了它。