C Programming -Linked List Implementation with characters


C Programming -Linked List Implementation with characters



MY CODE:


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

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

void main()
{ char A;
struct node *head,*ptr;
ptr=(struct node *)malloc(sizeof(struct node));
printf("Enter data for node 1 n");
scanf("%c",&ptr->data);
head=ptr;
int i=2;
while(1)
{
ptr->next=(struct node*)malloc(sizeof(struct node));
ptr=ptr->next;
printf("nEnter data for node %d:::n",i);
scanf("%c",&ptr->data);
ptr->next=NULL;
i=i+1;
printf("Do you want to continue Y OR N");
scanf("%c",&A);
if(A=='Y')
continue;
else
break;

}

struct node *temp;

temp=head;
while(temp!=NULL)
{
printf("%c=>",temp->data);
temp=temp->next;
}
printf("NULL");





}



For this code I can only enter the first character data after that it is skipping the scanf portion within the while loop.
But when I am doing the same code with integer it is giving me the right output.
Here if I replace the same code instead of having characters I replace it by integers it works fine.
I couldnt find a way to fix it.
Plz help.





Your problem isn't a linked list but incorrect use of scanf(). %c consumes a single character only and doesn't skip any whitespace (like newline). OTOH, %d does skip whitespace characters. See also my beginners' guide away from scanf()
– Felix Palmen
Jul 3 at 9:33



scanf()


%c


%d


scanf()





When you end the first input, do you not use the Enter key? That key will be put into the input buffer as a newline 'n' to be read by the next character input function.
– Some programmer dude
Jul 3 at 9:34


Enter


'n'





Thanks a lot now i replaced char with char[N] and used %s instead it is working fine
– Riju Mukherjee
Jul 3 at 17:03




1 Answer
1



As stated in the comments your problem lies not in the linked list implementation, but in the code lines here.


scanf("%c",&ptr->data); //line number 14

scanf("%c",&ptr->data); //line number 22

scanf("%c",&A); //line number 26



in all these lines %c consumes the new line character(n) instead of the users input.



To correct the issue, you can place a whitespace in front of the %c like this,


scanf(" %c",&ptr->data); //line number 14

scanf(" %c",&ptr->data); //line number 22

scanf(" %c",&A); //line number 26





thank you very much for your reply..it helped a lot
– Riju Mukherjee
Jul 6 at 16:33






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

api-platform.com Unable to generate an IRI for the item of type

How to set up datasource with Spring for HikariCP?

Display dokan vendor name on Woocommerce single product pages