0

I've been trying to creating singly linked list of strings but it does not work properly .But it works properly when I created linked list of integers. The first time its called perfectly. But when I execute the do while loop for second time by inputting choice=1 it messes up. The gets() does not accept the string from then

#include <stdio.h>
#include<string.h>
#include<stdlib.h>

#define ARR_MAX 20

struct node
{
        char info[ARR_MAX];
        struct node *next;
};
struct node *start=NULL;





void create()
{
        struct node *temp=NULL,*ptr=NULL;
        temp=(struct node *)malloc(sizeof(struct node));
        if(temp==NULL)
        {
                printf("Out of Memory Space:\n");
                exit(0);
        }
        else{
        printf("Enter the data value for the node %d:\n",i);
        i++;
       gets(temp->info);
       printf("%s \n",temp->info);
       printf("ok \n");
        temp->next=NULL;
        }
        if(start==NULL)
        {
                start=temp;
        }
        else
        {
                ptr=start;
                while(ptr->next!=NULL)
                {
                        ptr=ptr->next;
                }
                ptr->next=temp;
        }
}
void display()
{
        struct node *ptr;
 
        if(start==NULL)
        {
                printf("List is empty:\n");
                return;
        }
        else
        {
                ptr=start;
                printf("The List elements are:\n");
                while(ptr!=NULL)
                {
                        printf("%s \t",ptr->info );
                        ptr=ptr->next ;
                }
                printf("\n");
        }
}


int main(int argc, char const *argv[])
{
  int choice;
  do{
  create();
  printf("1.Create\n");
  scanf("%d",&choice);
  }while(choice==1);
  display();
  return 0;
}
tamizh
  • 1
  • 1
    [Stop using `gets`](https://en.cppreference.com/w/c/io/gets) it's so vile and evil it was removed from the standard. The only question you should harbor about `gets` is "why am I still using `gets`" ? That said, loop in `main` makes no sense. You hard-fire `create` before the user entered any choice, then fire it again if the choice was `1` (the reading of which leaving a newline in the input stream, and thus making the next `gets` effectively harbor a blank line). – WhozCraig Dec 29 '20 at 19:14
  • @amizh The problem is that after this call scanf("%d",&choice); the input buffer contains the new line character '\n' that is read by a next call of gets. So this call of gets will read an empty string. You need to remove the new ,line character from the input buffer. – Vlad from Moscow Dec 29 '20 at 19:19
  • Please ,read this :https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used – MED LDN Dec 29 '20 at 20:29

0 Answers0