#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#include<stdbool.h>
#include<math.h>
#include<time.h>
struct supplier{//供货商信息结构体 supplier.txt
char name[20];
char address[50];//地址
char phone[12];//电话
};
typedef struct supplier SUP;//简化,将"结构体类型"重新定义为SUP
struct link_supplier{
char name[20];
char address[50];//地址
char phone[12];//电话
struct link_supplier *next;
};
typedef struct link_supplier LSUP;
int main()//入库记录中的操作员暂且不赋值
{
FILE *fp;
fp=fopen("supplier.txt","wb+");
SUP *psup;
psup=(SUP*)malloc(sizeof(SUP));
strcpy(psup->name,"a");
fwrite(psup,sizeof(SUP),1,fp);
strcpy(psup->name,"b");
fwrite(psup,sizeof(SUP),1,fp);
strcpy(psup->name,"c");
fwrite(psup,sizeof(SUP),1,fp);
fclose(fp);
LSUP *hplsup,*plsup0,*plsup;//哨兵节点
hplsup=plsup0=(LSUP*)malloc(sizeof(LSUP));
hplsup->next=NULL;
fp=fopen("supplier.txt","rb+");
rewind(fp);
psup=(SUP*)malloc(sizeof(SUP));
while(fread(psup,sizeof(SUP),1,fp)!=0){//生成供货商信息链表
plsup0->next=plsup=(LSUP*)malloc(sizeof(LSUP));
plsup->next=NULL;
printf("生成链表过程中plsup->next!=NULL条件为%d\n",plsup->next!=NULL);
strcpy(plsup->name,psup->name);
strcpy(plsup->address,psup->address);
strcpy(plsup->phone,psup->phone);
plsup0=plsup;
}
fclose(fp);
char name[20];
printf("输入供货商名称\n");
scanf("%s",name);
plsup=hplsup;
int flag=0;
while(plsup->next!=NULL&&flag==0){//死循环
plsup=plsup->next;
printf("链表遍历中plsup->next!=NULL条件为%d\n",plsup->next!=NULL);
if(strcmp(plsup->name,name)==0){
flag=1;
}
}
return 55555555;
}
当输入的供货商名称不是a ,不是b ,不是c时,为什么会死循环?
fwrite(psup,sizeof(SUP),1,fp);
这些写入的位置都一样,会覆盖之前的
该回答引用GPTᴼᴾᴱᴺᴬᴵ
在代码中的死循环可能是由于没有对输入的供货商名称进行判断,而造成的。如果输入的供货商名称不是a、b、c之一,则在链表中无法找到对应的节点,但是循环条件中没有对这种情况进行判断,导致循环一直执行下去,直到遍历到链表末尾时才会退出循环。
为了避免死循环,可以在循环中加入判断条件,例如可以添加一个布尔变量found,初始值为false,当找到对应节点时,将其置为true,循环结束时检查该变量的值是否为true,如果是,则表示找到了对应节点,否则表示输入的供货商名称不在链表中,可以结束循环。代码示例:
char name[20];
printf("输入供货商名称\n");
scanf("%s",name);
plsup=hplsup;
int flag=0;
bool found = false; // 新增的变量
while(plsup->next!=NULL && !found){ // 添加 found 判断条件
plsup=plsup->next;
printf("链表遍历中plsup->next!=NULL条件为%d\n",plsup->next!=NULL);
if(strcmp(plsup->name,name)==0){
flag=1;
found = true; // 找到对应节点,将 found 置为 true
}
}
if(found) {
printf("找到对应节点\n");
} else {
printf("未找到对应节点\n");
}
这样就可以避免输入非a、b、c的供货商名称时的死循环问题。
不知道你这个问题是否已经解决, 如果还没有解决的话: