我有一个模块,可以搜索文件以查找索引,如果找到,则应该打印与该索引相关的详细信息。程序编译并运行,但无论患者是否保存,都打印未找到患者。我缺少什么逻辑错误?
注意: PatientCount 是一个全局变量,它会写入另一个文件并在每次添加患者时更新。
void patientSearch(struct patientRec patient[], struct apptRec appt[])
{
system("cls");
int c=0;
char search[6], admit;
printf("Enter the patient ID of the patient you would like to search for.\n");
scanf("%i", &search);
fflush(stdin);
FILE *fp;
fp=fopen("patients.txt", "r");
if(fp==NULL)
{
printf("\nError opening file!");
}
else
{
for (c=0; c<patientCount; c++)
{
if (search==patient[c].patientID)
{
printf("\nPatient found.\n\n");
printf("Patient ID: %i", patient[c].patientID);
fscanf(fp, "%s", patient[c].fName);
printf("\nPatient First Name: ");
puts(patient[c].fName);
fscanf(fp, "%s", patient[c].sName);
printf("\nPatient Surname: ");
puts(patient[c].sName);
fscanf(fp, "%i %c", patient[c].age, patient[c].sex);
printf("\nPatient Age: %i\nPatient Sex: %c", patient[c].age, patient[c].sex);
fscanf(fp, "%s", patient[c].notes);
printf("\n\nNotes: \n");
puts(patient[c].notes);
}
else
{
fscanf(fp, "\n");
}
}
}
fclose(fp);
if (c==patientCount)
{
printf("\nThis patient does not exist. Would you like to admit this patient?\n1: Yes\n2: No\n");
scanf(" %c", &admit);
if (admit=='1')
{
admitPatient(patient, appt);
}
}
}
最佳答案
char search[6], admit;
scanf("%i", &search);
if (search==patient[c].patientID)
更改为
int search; // This allows the rest of the code to match
或更改为
char search[6], admit; //Change the rest of the code to match
scanf("%s", &search);
if (strcmp(search, patient[c].patientID) == 0)
printf("Patient ID: %s", patient[c].patientID);
使您的输入和比较以相同的格式进行。
确保您的搜索数组足够大以包含最后的“\0”
关于c - 线性搜索保存到文件的结构中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35589124/