-
ASK
Hello guys,
im a IT student and i am studying C right now,
i have a problem in my program,
i have created a Struct Linked List to Store array data type
a program which store student data, input for name, nim, and, sex.
i try , it's no problem at all
but when i try to get it into a while loop,
second loop will result skip input for var name,
why this happen
idk..
i will be glad if u tell me why .. and give solution
sorry for my bad engliish, it's not my native.
Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct NodeStruct {
char*nama;
char*nim;
char*sex;
struct NodeStruct *next;
} Node;
void push(Node * head, Node * newNode) {
Node * current = head;
while (current->next != NULL) {
current = current->next;
}
}
void ql(){
printf("\napakah anda ingin menginput lagi ? ");
printf("\n1. Ya ");
printf("\n2. Tidak ");
printf("\nPilihanmu = ");
}
void
main (){
Node *node1 = NULL;
int q=1;
node1=(Node*)malloc(sizeof(Node));
node1->nama=(char*)malloc(sizeof(char));
node1->sex=(char*)malloc(sizeof(char));
node1->nim=(char*)malloc(sizeof(char));
printf("\nNama = "); gets(node1->nama);
printf("\nNIM = "); gets(node1->nim);
printf("\nJenis Kelamin (L/P) = "); gets(node1->sex);
node1->next=NULL;
while (q==1) {
Node *newNode;
newNode=(Node*)malloc(sizeof(Node));
newNode->nama=(char*)malloc(sizeof(char));
newNode->sex=(char*)malloc(sizeof(char));
newNode->nim=(char*)malloc(sizeof(char));
printf("\n\nNama = "); gets(newNode->nama);
printf("\nNIM = "); gets(newNode->nim);
printf("\nJenis Kelamin (L/P) = "); gets(newNode->sex);
newNode->next = NULL;
push(node1,newNode);
ql();
scanf("%d",&q);
}
}
-
That happens because you do scanf("%d",&q); at line #60. scanf() tends to leave the newline character behind, and the next time you call gets() it thinks that was the next line. Right after the scanf, do something like this to "flush" the input:
Code:
{
int c;
while ((c = getchar()) != '\n' && c != EOF) {
continue;
}
}
Now that I answered your question, please take a moment to read why some parts of your code should be changed:
Why gets() is bad
Casting malloc
void main() - the Wrong Thing
Also these:
Importance of code indentation
How to ask questions the smart way