How can I exit a while
loop?
I tried NULL, '\0' and '\n' but nothing works. I am trying to exit the loop if user types empty line or null character. I used == NULL but it doesn't go into the loop.
How should I exit the fgets
loop?
Code
typedef struct node{
char *num;
struct node *next;
}Node, *NodePtr;
NodePtr makeNode(char *n){
NodePtr np = (NodePtr) malloc(sizeof(Node));
np -> num = n; // (*np).num
np -> next = NULL;
return np;
}
// prints all the items in the list
void printList(NodePtr np){
while(np != NULL){ // as long as there's a node
printf("%s\n",np ->num );
np = np -> next; //go on to the next node
}
}// end print list
// main function
int main(void){
char n[10];
NodePtr top,np,last;
top = NULL;
if(fgets(n,sizeof n,stdin) != NULL){
while(n != '\0'){
np = makeNode(n); // create a new node containing n
if(top == NULL){ // set top if first node
top = np;
}
else{
last->next = np; // set last-> next for other nodes
}
last = np; //keepin track of last node
if(fgets(n,sizeof n,stdin) != NULL){
//do nothing
printf("User enter null\n" );
}
}
}
printList(top);
return 0;
} // end main