Reputation: 904
I am only able to view the very first element of the input.The code is given as follows:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct d_list{
int data;
struct d_list *next;
struct d_list *prev;
}node;
// Without recursively calling the insert function.
typedef node *list;
main(){
printf("Enter data(y/n)?");
char ch;
scanf("%s",&ch);
int n;
list head;
list temp;
list tail;
head=tail=temp=NULL;
if(ch=='y'||ch=='Y'){
printf("Enter data");
scanf("%d",&n);
temp=(list)malloc(sizeof(node));
temp->data=n;
temp->next=temp->prev=NULL;
head=temp;
tail=temp;
}
printf("Enter more data..?(y/n)");
scanf("%s",&ch);
while(ch=='y'||ch=='Y'){
printf("Enter data");
scanf("%d",&n);
temp=(list)malloc(sizeof(node));
temp->data=n;
temp->prev=tail;
temp->next=NULL;
tail->next=temp;
tail=temp;
printf("Enter more data..?(y/n)");
scanf("%s",&ch);
}
temp=head;
while(temp!=NULL){
printf("%d",temp->data);
temp=temp->next;
}
getch();
}
I want to display all the inputs in the order they were input.What is the problem here?
Upvotes: 2
Views: 102
Reputation: 912
Try this, simplest code for your problem, the changes I have made are,
changed scanf("%s",&ch); to scanf("%c",&ch);
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define _CRT_SECURE_NO_WARNINGS
using namespace std;
typedef struct d_list{
int data;
struct d_list *next;
struct d_list *prev;
}node;
typedef node *list;
int main()
{
char ch;
int n;
list head = NULL,temp = NULL,tail = NULL;
do{
printf("\nEnter data ?(y/n):\n");
scanf("%c",&ch);
if(ch=='n'||ch=='N')
break;
printf("\nEnter data :\n");
scanf_s("%d",&n);
temp=(list)malloc(sizeof(node));
temp->data=n;
temp->next=NULL;
if(head == NULL)
{
temp->prev=NULL;
head=temp;
}
else
{
temp->prev=tail;
tail->next=temp;
}
tail=temp;
}while(ch=='y'||ch == 'Y');
temp=head;
while(temp!=NULL){
printf("\n%d",temp->data);
temp=temp->next;
}
getch();
return 0;
}
Upvotes: 1
Reputation:
Your logic of the code is correct but here is the error: make scanf("%s",&ch);
as scanf(" %c",&ch);
Upvotes: 3