getchar() not accepting input - c

I am writing a program to implement a linked list in C.Here is my program.
/*Implementing a singly linked list in c*/
#include<stdio.h>
#include<stdlib.h>
#include<alloca.h>
struct node{
int data;
struct node* link;
}*start=NULL;
void main(){
char choice;
int data;
do{
printf("Enter data\n");
scanf("%d",&data);
struct node* temp;
temp=(struct node*)malloc(sizeof(struct node));
temp->data=data;
temp->link=NULL;
if(start==NULL)
start=temp;
else
{
struct node* traversing_pointer;
traversing_pointer=start;
while(traversing_pointer!=NULL)
traversing_pointer=traversing_pointer->link;
traversing_pointer->link=temp;
}
printf("Do you want to enter more");
choice=getchar();
}
while(choice=='y'|| choice=='Y');}
I basically want at least one node in the linked list to be created, that is why I am using a do, while loop. But after the first data input the program terminates without accepting an input for choice variable. Here is my output. What can be the
Enter data
45
Do you want to enter more
RUN FINISHED; exit value 10; real time: 2s; user: 0ms; system: 0ms
What can be the possible error?

To consume the newline character left in the input stream, do:
scanf("%d",&data);
getchar(); //To consume a newline
or use a loop to read all newlines.
scanf("%d",&data);
int c=0;
while ((c = getchar()) != '\n' && c != EOF) ; // Read & ignore all newlines
Another problem I see is you are not linking the nodes properly. You want to link the new node as the last one. So you have to traverse till the last node (not till you reach NULL). Change the loop condition to:
while(traversing_pointer->link!=NULL)
traversing_pointer=traversing_pointer->link;
traversing_pointer->link=temp;

It is because your getchar reads the end of line you've entered by pressing Enter after the 45 input.

Related

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.
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

Linked List issue - Why is it adding a 0 as a element to my list when the user types in 'N to quit adding more elements?

So I working on creating a function called 'Create' that asks the user to enter numbers for a linked list. If the user types in 'Y', then ask to enter another element else if the user types 'N' stop and display the linked list, but I am having a bit of trouble. When I run it, it doesn't give me the option to type in Y or N and also when I type in N, it adds a 0 to the linked list. What is happening?
#include <stdio.h>
#include <stdlib.h>
//-------------------------------------------------
struct node {
int data;
struct node *next;
}*start=NULL;
//------------------------------------------------------------
void create() {
char ch;
do {
struct node *new_node,*current;
new_node=(struct node *)malloc(sizeof(struct node));
printf("Enter the data : ");
scanf("%d",&new_node->data);
new_node->next=NULL;
if(start==NULL) {
start=new_node;
current=new_node;
} else {
current->next=new_node;
current=new_node;
}
printf("Do you want to create another?(Y\N) ");
ch = getchar();
} while(ch!='N');
}
//------------------------------------------------------------------
void display() {
struct node *new_node;
printf("The Linked List : ");
new_node=start;
while(new_node!=NULL) {
printf("%d--->",new_node->data);
new_node=new_node->next;
}
printf("NULL\n");
}
//----------------------------------------------------
int main() {
create();
display();
}
1- move the declaration of struct node *new_node, *current; to outside the do loop (to just before the do), because you want them to keep their values between iterations.
2- a newline character remained in the buffer after the scanf that read the number, because the user had to type return after the number, and the scanf did not consume it. To skip this newline when getting the Y/N answer, get your Y/N answer in this way instead of ch = getchar();:
scanf(" %c", &ch); // notice the blank before the %c, important to skip the newline that remained in the buffer
3- although not necessary, better avoid using the escape character \ in your question, use "Y/N" instead of "Y\N"
Your code worked perfectly after I made these modifications.

weird number appears on output-C

I have made a simple list like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
struct node{
int am;
struct node *next;
};
typedef struct node node;
int main(){
int n;
node *head=(node *)malloc(sizeof(node));
node *cur=head;
printf("Give me a number:\n");
scanf(" %d",head->am);
cur=head;
while(1){
printf("Give me a number\n");
scanf(" %d",&n);
if(n==0)
break;
cur->am=n;
cur->next=(node *)malloc(sizeof(node));
cur=cur->next;
cur->next=null;
}
travel(head);
printf("Total nodes available :%d\n",count(head));
system("pause");
return 0;
}
Now travel is supposed to go through each node in the list and display the integer saved in each node.
void travel(node *h){
if(h==NULL)
return;
printf("Received data from node: \t %d\n",h->am);
travel(h->next);
}
Now the problem is that when travel is called it wont print the integer from the first node.It will also print another "Received data from node:" followed by a strange number.
For example
If i give 1,2,3,4 as inputs these are the results
Received data from node: 2
Received data from node: 3
Received data from node: 4
Received data from node: 4026432
Any ideas?
Now the problem is that when travel is called it wont print the
integer from the first node
This can be precisely known from this part of the main() function
printf("Give me a number:\n");
scanf(" %d",head->am); //this is wrong use of scanf("%d",&head->am);
cur=head;
while(1){
printf("Give me a number\n");
scanf(" %d",&n);
if(n==0)
break;
cur->am=n;
as I've mentioned you're scanning wrongly but that doesn't matter because later in the code in while loop you replace it this way...
you scan number and store it at head->am
then you assign head to cur so head->am and cur->am are both the same now... so in while loop when you first assign n to cur->am, it gets assigned to head->am. so this explains why you never get to print first node.
Solution:
to overcome it ... in while loop, before assigning cur->am=n try doing:
cur->next=(node *)malloc(sizeof(node));
cur=cur->next;
//then... assign
curr->am=n;
this way you'll not lose first node.
suggestion:
As someone has already said it's much easier to traverse/ travel the list using loops (never mind... if you want to do it recursively)
here's how you do it with the loops:
void travel(node *h)
{
if(h==NULL)
return; //list is empty,consider printing "list empty" :)
while(h!=NULL)
{
printf("Received data from node: \t %d\n",h->am);
h=h->next;
}
}
To put all together your code without changing the travel() function as suggested would be:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int am;
struct node *next;
};
typedef struct node node;
void travel(node *h);
int main() //I have a habit of returning values from main() :)
{
int n;
node *head=(node *)malloc(sizeof(node));
node *cur=head;
printf("Give me a number:\n");
scanf(" %d",&head->am);
cur=head;
while(1)
{
printf("Give me a number\n");
scanf(" %d",&n);
if(n==0)
break;
cur->next=(node *)malloc(sizeof(node));
cur=cur->next;
cur->am=n; //NOTE:here's the change!
cur->next=NULL;
}
travel(head);
return 0; //just to signify successful compilation
}
void travel(node *h)
{
if(h==NULL)
return;
printf("Received data from node: \t %d\n",h->am);
travel(h->next);
}
Sample Input : 5 6 3 1 0
Sample Output :
Give me a number:
5
Give me a number
6
Give me a number
3
Give me a number
1
Give me a number
0
Received data from node: 5
Received data from node: 6
Received data from node: 3
Received data from node: 1
There are (at least) those issues:
The line scanf(" %d",head->am) is wrong since scanf() expects an address of the memory location of the expected value meaning &head->am.
Your loop scans a number and puts it in the current node and only after it creates a new node. Therefore, the first number you enter will be overridden (after fixing the first issue) and the last node created will contain random data because the loop will terminate after entering 0 but before putting anything in the last node.
I propose like this:
int main(void){
int n;
node anchor = {0, NULL};//dummy head
node *head, *cur = &anchor;
while(1){
printf("Give me a number\n");
scanf("%d", &n);
if(n==0)
break;
cur->next = malloc(sizeof(node));
cur = cur->next;
cur->am = n;
cur->next = NULL;
}
head = anchor.next;
travel(head);
printf("Total nodes available :%d\n", count(head));
return 0;
}
You are missing & at the first scanf:
scanf(" %d", &head->am);
But it could be made to do all the scanf inside the while:
int main(){
node *head=0;
node *cur=0;
node *prev=0;
while(1){
prev = cur;
cur=(node *)malloc(sizeof(node));
cur->next=NULL;
printf("Give me a number\n");
scanf("%d",&cur->am);
if(cur->am==0)
break;
if(head == NULL) head = cur;
if(prev != NULL) prev->next = cur;
}
travel(head);
printf("Total nodes available :%d\n",count(head));
return 0;
}
I hope I didnt make any mistake as I wrote it in this SO editor..
and as someone said, you should free the linked list .. but thats out of scope here..
HTH

Creating and adding data in a linked Llist

I have started learning about Linked Lists, which through videos and multiple examples I have pretty much understood what a Linked List is and how it can be represented in a real life analogy. But when it comes to coding it I get lost I suppose through all the pointers I kind of get confused, it took a bit for me to get a stronger grasp on arrays so I assume it will be the same with Linked lists. So here is my code
/*
• The program will use dynamic memory to create a singly linked list(NO ARRAYS PERMITTED)
• The program will store unlimited number of student records(limited only by RAM).
• A student record will consist of Student Name, Age, and GPA…you may need to add additional fields to make this work(Next).
• The program will have a way for the user to add records(in order by name).You can assume that no two students have the same name.The list will always be in order.
• The program will have a way for the user to display ALL records.
• The program needs a way to quit.
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#pragma warning(disable: 4996)// disables warning
typedef struct{
char name[40];
int age;
float gpa;
struct NODE* next;
}NODE;
void addStudent();
int main(void){
NODE* head = NULL;
int userinput;
printf(" **********************************\n");
printf(" * MENU *\n");
printf(" * 1. Add Student *\n");
printf(" * 2. Display all student records*\n");
printf(" * 3. Quit *\n");
printf(" **********************************\n");
scanf_s("%d%*[^\n]", &userinput); '\n' == getchar();
switch (userinput)
{
case 1: do
{
addStudent(head);
printf("Add another record? 1(y) 2(n)\n");
scanf_s("%d%*[^\n]", &userinput); '\n' == getchar();
} while (userinput == 1);
break;
}
}
void addStudent(NODE* head){
head = malloc(sizeof(NODE));
if (head == NULL)
{
return;
}
NODE * current = head;
printf("Please Enter student name:\n");
fgets(current->name, 40, stdin);
printf("Enter student age:\n");
scanf("%d%*[^\n]", &current->age); '\n' == getchar();
printf("Enter student gpa:\n");
scanf("%f%*[^\n]", &current->gpa); '\n' == getchar();
current->next;
current->next = NULL;
while (current != NULL){
current = head;
printf("%s\n", current->name);
printf("%d\n", current->age);
printf("%0.2f\n", current->gpa);
current = current->next;
}
}
When I compile, it will always print the head I assume its because of current = head within the while loop, I understand why its printing the head over but I am lost on how to arrange this code So that I can create a new node when I add and print all the nodes, through the loop.
The problem is that you never create new nodes to add to the list but always just updating the head. In order to make it work you should:
Allocate a new NODE,
NODE *newNode = malloc(sizeof(NODE));
Load the data into this node
printf("Please Enter student name:\n");
fgets(&newNode->name, 40, stdin);
printf("Enter student age:\n");
scanf("%d%*[^\n]", &newNode->age); '\n' == getchar();
printf("Enter student gpa:\n");
scanf("%f%*[^\n]", &newNode->gpa); '\n' == getchar();
Update the node to point to the node currently pointed by the HEAD
newNode->next = head
Update the head to point to the new Node
head = newNode;

while() loop not working as expected. What could be the reason?

I have started coding Linked list in C. My code is as follows:
#include<stdio.h>
#include<malloc.h>
struct node
{
int data;
struct node *next;
};
struct node * create(struct node *);
display(struct node *);
int main()
{
struct node *head=NULL;
head = create(head);
display(head);
getch();
return 0;
}
struct node * create(struct node *Head)
{
struct node *temp;
char ch='y';
int i=1;
while(ch=='y')
{
temp=malloc(sizeof(struct node));
temp->data=i*10;
temp->next=Head;
Head=temp;
printf("\nAdded node : %d",Head->data);
printf("\nContinue to add more nodes ? : ");
scanf("%c",&ch);
}
return Head;
}
display(struct node *Head)
{
while(Head!=NULL)
{ printf("%d\t%d\n",Head->data,Head->next);
Head=Head->next;
}
}
The problem that I am facing is that after entering into the function "create" and creating just one node, my program jumps back to main, then jumps to "display" function and then jumps back to function "create" at the line where it asks me whether I want to continue. At this point, when I do enter "y", program just exits!
Why this sorta behaviour??
Someone please explain me how the control flows and why is my program going haywire!!!
Reason:
This happens because when you type in 'y' and then hit enter, a newline character '\n' gets buffered and will be read on the next iteration of scanf(). This will cause while(ch=='y') to evaluate to false (since now ch == '\n'), breaking off the loop.
Normally scanf() would skip whitespaces and newlines before hitting the expected value. However, when you use the character format %c, this doesn't happen, as newlines and whitespaces are also valid characters.
How to fix:
You can fix it by using scanf(" %c",&ch);. The space before %c will skip any leading backspace or newline characters found on the buffer before actually reading the value.

Resources