如何在队列中退出while循环?

时间:2015-04-09 03:14:59

标签: c while-loop exit fgets

如何退出while循环?

我尝试过NULL,' \ 0'和' \ n'但没有任何作用。如果用户键入空行或空字符,我试图退出循环。我使用== NULL但它没有进入循环。

我该如何退出fgets循环?

代码

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

1 个答案:

答案 0 :(得分:1)

看起来n是指向char数组的指针。考虑尝试检查

while(!(n[0] == '\0') && !(n[0] == '\n'))

检查新行和空字符