Home > Net >  this code expects two input after calling create function
this code expects two input after calling create function

Time:11-05

//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;
}

I don't know why but after calling function printf command is executed and terminal asks me to input data in linked list but after inputting some data it again expects some input. I seriously don't know what to try anymore.

CodePudding user response:

The problem is how you're reading the input in create:

scanf("%d ",&num);

A space in the format string matches any number of whitespace characters. So if you enter a number followed by a newline, scanf will wait until you enter a non-whitespace character.

This can be fixed by removing the space from the format string.

scanf("%d",&num);
  • Related