This program should allow the user to input some names (until the user wishes to continue.) and then display those names in ascending order. I have used the strncmp function in comparing the char arrays. But when this is run, only the 1st and last name of the sorted name list is given as the output (which means, the list was sorted). But I cannot find out why the names in between them aren't displayed. Please help me! Thank you.
#include <stdio.h>
#include <malloc.h>
#include <string.h>
char name[10];
int place;
struct node
{
char nm[10];
struct node *next;
}*newnode, *prev, *temp, *display, *current, *list;
void createlist()
{
list = NULL;
}
;
void insert()
{
newnode = (struct node*) malloc(sizeof(struct node));
printf("Enter the Name: ");
scanf("%s", &name);
strncpy(newnode->nm, name, 10);
newnode->next = NULL;
if (list == NULL )
{
list = newnode;
}
else if (strncmp(name, list->nm, 10) < 0)
{
newnode->next = list;
list = newnode;
}
else
{
temp = list;
place = 0;
while (temp != NULL && place == 0)
{
if (strncmp(name, temp->nm, 10) >= 0)
{
prev = temp;
temp = temp->next;
}
else
{
place = 1;
}
newnode->next = prev->next;
prev->next = newnode;
}
}
}
void displayname()
{
if (list == NULL )
printf("\n\nList is empty");
else
{
display = list;
while (display != NULL )
{
printf("%s\n", display->nm);
display = display->next;
}
}
}
int main()
{
char choice;
choice == 'y';
createlist();
do
{
insert();
printf("Do you want to continue? ");
scanf("%s", &choice);
} while (choice = 'y' && choice != 'n');
displayname();
}
In your insert function, you are useing
use like
[EDIT]
Use your insert function like this.
Now do remember one thing, In your code,
in main() your are doing
choice == 'y'; that is not assignment. You should use
choice = 'y';
in your main(), in do{}while() your are using
while (choice = 'y' && choice != 'n'); choice ='y' is assignment, not comparison. use like this
while (choice == 'y' && choice != 'n');
in main(), you are using
scanf("%s", &choice); // choice is a char, you are trying to have string (%s) here. That will memory corruption So use it like this,
choice = getche();