C 搜索文件并将其包含的字符串与输入的变量进行比较

C 搜索文件并将其包含的字符串与输入的变量进行比较,c,file,stdio,string.h,C,File,Stdio,String.h,我试图搜索一个包含一组人的信息的文件,例如:他们的名字、姓氏和ID 我正在提示用户输入他们的ID代码。程序应搜索文本文件,并确保其代码与文件中的代码匹配,以便通过比较文件中的字符串和用户输入的变量,程序可以继续 我不知道如何实现这一点。下面是代码片段: #include <stdio.h> #include <conio.h> #include <string.h> typedef struct record { char (fname[3])[20];

我试图搜索一个包含一组人的信息的文件,例如:他们的名字、姓氏和ID

我正在提示用户输入他们的ID代码。程序应搜索文本文件,并确保其代码与文件中的代码匹配,以便通过比较文件中的字符串和用户输入的变量,程序可以继续

我不知道如何实现这一点。下面是代码片段:

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

typedef struct record {
  char (fname[3])[20];
  char (lname[3])[20];
  int code[3];
} information;

int main (void) {
  char ffname[20], flname[20];
  int fID, i;
  FILE *kfile;

  if ((kfile = fopen("C:\\Users\\Student\\Downloads\\information.txt","r")) == NULL) {
    perror("Error while opening file");
  } else {
    printf("%-20s %-20s %s\n", "First Name", "Last Name", "ID");
    fscanf(kfile, "%19s %19s %d", ffname, flname, &fID);
    printf("\n");
    while (!feof(kfile)) {
      printf("%-20s %-20s %04d\n", ffname, flname, fID);
      fscanf(kfile, "%19s %19s %d", ffname, flname, &fID);
    }
    fclose(kfile);
  }

  information info;
  for (i = 0; i < 3; i++) {
    printf("Please enter your ID.");
    scanf("%04d", &info.code);
  }
  getch();
  return 0;
}

我不确定我是否理解您的问题,但您可以尝试以下方法:

typedef struct record {
  char *fname;
  char *lname;
  int code;
} information;

int main (void) {
  char ffname[28], flname[28];
  int fID, i, id_;
  information array[3];
  FILE *kfile;
  i = 0;

  if ((kfile = fopen("C:\\Users\\Student\\Downloads\\information.txt","r")) == NULL) {
    perror("Error while opening file");
  } else {
    while (!feof(kfile)) {
      fscanf(kfile, "%s %s %d", ffname, flname, &fID);
      array[i].fname = strdup(ffname);
      array[i].lname = strdup(flname);
      array[i].code = fID;
      i++;
    }
    fclose(kfile);
  }

  printf("Please enter your ID: ");
  scanf("%d", &id_);
  for (i = 0; i < 3; i++) {
    if (array[i].code == id_) {
      // print the record
      printf("%s %s \n", array[i].fname, array[i].lname);
    }
  }
  return 0;
}

你的档案有多大?里面有多少张唱片。文本的格式如何?你是否控制文本的格式,或者它是第三方提供给你的文件?因此,你阅读文件并显示它,一旦它结束,你要求ID?三次读取同一ID??没有非常用户友好!你在哪里搜索数据呢?