-2

我正在尝试搜索包含一组人信息的文件,例如:他们的名字、姓氏和 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;
}
4

1 回答 1

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;
}
于 2015-02-25T21:19:18.687 回答