c - 如何退出队列中的 while 循环?

标签 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

最佳答案

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

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

检查新行和空字符

关于c - 如何退出队列中的 while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29529131/

相关文章:

c - 在c/cocoa中读取和输出UTF-8字符串

c - 由于 fgets 导致段错误(核心转储) - 我认为

c++ - cin.fail while循环输入再入

function - 退出 PowerShell 函数但继续执行脚本

c - 在传统的 Linux fork-exec 中使用 _exit() 和 exit() 有什么区别?

c - 如何在 C 中将 double 组转换为整数数组?

c - 理解Linux中的fork()

while-loop - while (true) 与break 是不好的编程习惯吗?

Java 数组创建和数组名称更改

ruby-on-rails - 在 Ruby on Rails IRB 中停止加载脚本执行的最佳方法