如何在C语言中搜索String

时间:2014-02-16 15:14:28

标签: c file-handling

我正在用C开发学生管理系统,但我似乎无法完成搜索功能。写入文件工作正常,但按名称搜索不起作用。输入名称并退出程序时没有任何反应。

到目前为止,这是我的代码:

#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>

struct student {
    int id;
    char name[10];
    int semester;
};

int main(void) {
    char name[10], c[100];
    struct student s;
    FILE *fp;
    int choice;

    printf("Enter 1 to Add record\nEnter 2 to Search \n");
    scanf("%d", &choice);

    switch(choice) {
        case 1:
            fp = fopen("std.txt", "a");
            printf("\nEnter id: ");
            scanf("%d", &s.id);
            fflush(stdin);
            printf("\nEnter name: ");
            scanf("%s", &s.name);
            fflush(stdin);
            printf("\nEnter semester: ");
            scanf("%d", &s.semester);
            fflush(stdin);

            fprintf(fp, "\nId: %d\tName: %s\tSemester: %d\n", s.id,s.name,s.semester);
            fclose(fp);
            break;

        case 2:
            fp=fopen("std.txt","r");
            printf("ENTER THE NAME ");
            scanf("%s",&name);
            while(feof(fp)) {
                if(strcmp(name, s.name) == 0) {
                    printf("\n\t%d\t %s\t %d", s.id, s.name, s.semester);
                    getch();
                    break;
                }
            }
            fclose(fp);
            getch();
            break;

        case 3:
            exit(1);
    }
    getchar();
} 

2 个答案:

答案 0 :(得分:0)

你实际上并没有读到学生结构中的这一行。您可能希望文件中的每一行fgetsscanf并将其加载到struct student s

答案 1 :(得分:0)

使用fwrite和fread的样本

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct student {
    int id;
    char name[10];
    int semester;
};

int main(void) {
    char name[10], c[100];
    struct student s;
    FILE *fp;
    int choice;

while(1){
    printf("Enter 1 to Add record\nEnter 2 to Search \nEnter 3 to Exit\n");
    scanf("%d", &choice);

    switch(choice) {
        case 1:
            fp = fopen("std.txt", "ab");
            printf("\nEnter id: ");
            scanf("%d", &s.id);
            fflush(stdin);
            printf("\nEnter name: ");
            scanf("%s", &s.name);
            fflush(stdin);
            printf("\nEnter semester: ");
            scanf("%d", &s.semester);
            fflush(stdin);

            //fprintf(fp, "\nId: %d\tName: %s\tSemester: %d\n", s.id,s.name,s.semester);
            fwrite(&s, sizeof(s), 1, fp);
            fclose(fp);
            break;

        case 2:
            fp=fopen("std.txt","rb");
            printf("ENTER THE NAME ");
            scanf("%9s", name);
            getchar();
            while(fread(&s, sizeof(s), 1, fp)==1) {
                if(strcmp(name, s.name) == 0) {
                    printf("\n\t%d\t %s\t %d\n", s.id, s.name, s.semester);
                    break;
                }
            }
            fclose(fp);
            break;

        case 3:
            exit(1);
    }
}
    getchar();
}