【问题标题】:this code expects two input after calling create function此代码在调用 create 函数后需要两个输入
【发布时间】:2021-12-18 22:37:23
【问题描述】:
//linked list
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <conio.h>

struct node
{
    int data;
    struct node *next;
};

struct node *head = NULL;

struct node *create(struct node *head);

int main()
{
    int n;
    printf("enter your slection");
    printf("\n 1.create a linked list");
    scanf("%d", &n);

    switch (n)
    {
        case 1:
        head = create(head);
        printf("linked list has been created");
        break;

        default:
        break;
    }

    return 0;
}

struct node *create(struct node *head)
{
    struct node *newnode, *ptr;
    int num;
    printf("enter data of node");
    scanf("%d ",&num);
    newnode = (struct node *)malloc(sizeof(struct node *));

    if (newnode != NULL)
    {
        head=newnode;
        newnode->data=num;
        newnode->next=NULL;
    }

    return head;
}

我不知道为什么,但在调用函数printf 命令执行后,终端要求我在链表中​​输入数据,但在输入一些数据后,它再次需要一些输入。我真的不知道该尝试什么了。

【问题讨论】:

  • 这能回答你的问题吗? Why aren't students taught to use a debugger?
  • 无论如何,我建议使用您的调试器并检查您的程序的去向。您应该学习如何使用您的调试器,因为它会在大多数情况下为您提供帮助。
  • 如果在每个 printf() 格式化字符串的末尾(而不是开头)放置一个 \n 换行符,会更容易看到发生了什么。
  • Rishi Patel,谁或什么文字建议在 "%d " 中编码一个空格?
  • 您的所有建议都已得到妥善记录,我现在将认真学习使用调试器

标签: c linked-list


【解决方案1】:

问题在于您如何读取create 中的输入:

scanf("%d ",&num);

格式字符串中的空格匹配任意数量的空白字符。因此,如果您输入一个数字后跟一个换行符,scanf 将等到您输入一个非空白字符。

这可以通过从格式字符串中删除空格来解决。

scanf("%d",&num);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-23
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    • 2014-04-28
    • 2012-02-06
    • 2019-01-31
    • 1970-01-01
    相关资源
    最近更新 更多