c - 线性搜索保存到文件的结构中的元素

标签 c file data-structures scanf linear-search

我有一个模块,可以搜索文件以查找索引,如果找到,则应该打印与该索引相关的详细信息。程序编译并运行,但无论患者是否保存,都打印未找到患者。我缺少什么逻辑错误?

注意: 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/

相关文章:

algorithm - 如何聚类大型数据集

c - 为什么我在以下代码中遇到段错误(核心转储)?

c++ - 如何在 VS Code 中编译 c/c++ 时禁用自动创建 exe 文件?

linux - 伪设备文件的重要性是什么?我应该在什么情况下使用它们?

python - 如何从包含来自多个来源的多个词典的列表中创建数据框

c - 在句子(具有多个单词)中查找多单词字符串(关键字)的优化算法或方法?

c++ - 如何直接从分配的内存中执行 mmaped 二进制/代码

c - 为什么要在这条线上投两次?

node.js - Nodejs 14.5 文件系统 API Dirent "Symbol(type)"属性是什么?

python - Python 2 和 Python 3 中 print 的细微差别