【问题标题】:character variable storing issue with scanfscanf的字符变量存储问题
【发布时间】: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()

标签: c++ c char scanf cin


【解决方案1】:

我不确定原因,但只需在您的 scanf("%c",&amp;ch) 中添加一个空格,它就会开始工作。 只需将其更改为scanf(" %c",&amp;ch) 您可以在某处检查是否有原因并将其注释掉,但现在这将对您有所帮助。只是猜测可能是ch 读取的新字符是新的行,它本身终止了它。

【讨论】:

    猜你喜欢
    • 2017-02-11
    • 1970-01-01
    • 2012-07-10
    • 2014-02-07
    • 2012-11-22
    • 2014-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多