gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:21:38 25 4
gpt4 key购买 nike

如何退出 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com