【问题标题】:Search file and compare strings it contains with inputted variable搜索文件并将其包含的字符串与输入的变量进行比较
【发布时间】:2015-02-25 20:24:08
【问题描述】:

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

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

我不确定如何实现这一点。下面是sn-p的代码:

#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;
}

【问题讨论】:

  • 您的文件有多大?里面有多少条记录。文本是如何格式化的?您控制文本的格式还是第三方提供给您的文件?
  • 所以你读取文件并显示它,一旦它结束你要求ID?三遍读同一个ID??不是很人性化!您实际上在哪里搜索数据?

标签: c file stdio string.h


【解决方案1】:

我不确定我是否理解你的问题,但你可以试试这个:

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-17
    • 1970-01-01
    • 2014-04-12
    • 2018-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多