I'm writing a program to create a linked list node. After that, i add some functions (insert,search,update,and print). The linked list contains number, name, and quantity on hand.
The main function prompts users to enter an operation code, then calls a function requested actions.
main()
{
char code;
int c;
for(;;)
{
printf("i: insert\ns: search\nu: update\np: print\n");
printf("Enter operation code: ");
scanf("%c",&code);
while((c=getchar() )!= '\n'&& c!=EOF);
switch(code)
{
case 'i': insert();
break;
case 's': search();
break;
case 'u': update();
break;
case 'p': print();
break;
case 'q':return 0;
default: printf("Illegal code\n");
break;
}
printf("\n");
}
}
All function work correctly. However, in the insert function, I use fgets statement to get the string input from the user. (NAME_LEN = 25)
void insert()
{
node *previous,*current,*new_node;
new_node = malloc(sizeof(node));
printf("Enter part number: ");
scanf("%d",&new_node->number);
for(current = inventory,previous=NULL;
current != NULL&& new_node->number > current->number;
previous = current,current = current -> next);
if(current != NULL && new_node ->number == current->number)
{
printf("Part already exists.\n");
free(new_node);
return;
}
printf("Enter name part: ");
fgets(new_node->Name,NAME_LEN+1,stdin); // i use fgets to input string name
printf("Enter quantity on hand: ");
scanf("%d",&new_node->on_hand);
new_node -> next = current;
// move to the next node
if(previous == NULL)
inventory =new_node;
else
previous->next = new_node;
}
Unfortunately, this code doesn't work. The program shows that
i: insert
s: search
u: update
p: print
Enter operation code: i
Enter part number: 2
Enter name part: Enter quantity on hand: 3
As you can see that, the name part was missed.
Moreover, after inserting a new node, the program automatically shows the default case in the switch.
i: insert
s: search
u: update
p: print
Enter operation code: i
Enter part number: 2
Enter name part: Enter quantity on hand: 3
i: insert
s: search
u: update
p: print
Enter operation code: Illegal code
Can you explain to me what happens, pls?.