c - 在文本文件中搜索 ID (Turbo c)

标签 c turbo-c

我有这个小作业:

Given a text file, create a function that searches for a specific ID provided by the user, inside the file. If it exists, print the entire profile as follows:

ID_genre_name_age_height

在文本文件中只有一个配置文件:

19800372_male_David_19_1.75

因此,如果我输入相同的 ID,我的函数应该打印该信息。

我的代码,到目前为止不起作用,如下所示:

#include <conio.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <iostream.h>
 int menu ();

main ()
{
int dato;
void create();
void Store();
void read();
void search();

clrscr();
   do
{
    dato=menu();
    switch (dato)
    {
        case 1:
            create();
            break;
        case 2:
            store();
            break;
        case 3:
            read();
            break;
        case 4:
            search();
            break;

        case 5:
            return -1;


        default: cout<<"\n Error";
             getch ();
             break;
      }

    }
    while (dato !=5);

    getch();
    return 0;

}

int menu ()
{
     int op;
     clrscr();
     cout<<"\n File creator system";
     cout<<"\n1 Create a file";
     cout<<"\n2 Store Information";
     cout<<"\n3 Read a file";
     cout<<"\n4 Search Information";
     cout<<"\n5 Exit...\n";
     cout<<"\n";
     cin>>op;

     return op;
}
.
.
.
.

  void search()
   {
    char ID[10],
    char ID1[10];
    char genre[10];
    char name[20];
    int age;
    float height;


 FILE *in;
 in=fopen("c:\\exercise.txt","r");

  clrscr();
  printf("Enter ID: ");
   fgets (ID1,10,stdin);

 do{
    fscanf(in,"%9s %s %s %d %4s",ID,genre,name,age,height);
  if (strcmpi(ID,ID1)==0)
   {
    printf("ID:%9s\n",ID);
    printf("Genre:%s\n",genre);
    printf("Name:%s\n",name);
    printf("Age:%d\n",age);
    printf("Height:%4s\n",height);
   }
  }while(!feof(in));
 fclose(in);


 getch();
 }  

我不明白为什么它不起作用,我输入了 ID,但它仍然存在。

最佳答案

  1. 检查fopen 是否成功。

  2. 如果您的输入文件具有:ID_genre_name_age_height 那么这将被视为单个字符串。由于您似乎将它们读入变量,因此您应该将输入文件作为空格分隔的字符串列表。

  3. 您的所有变量都是字符数组,但您对某些未定义行为使用了 %f。适本地更改您的变量类型。

  4. 检查 fscanf() 的返回值,看没有读取错误。

  5. feof 告诉您是否读取了输入文件,而不是文件末尾。这意味着循环将比您期望的多执行一次。考虑像 fgets 这样的东西,然后执行 sscanf()

关于c - 在文本文件中搜索 ID (Turbo c),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12789701/

相关文章:

c语句中的编译错误

c - 链表的指针变量 : difference between the variable, 对该变量的引用,以及指向该变量的指针

c - 结构中指针变量的大小

c - 执行 while 循环错误信息(身份错误)

c - 指针记法题

c - 指向整数数组的指针数组

c - 我希望 vector_total 没有任何重复的数字

c++ - C/C++预处理器宏可以有默认参数值吗?

c - 这是一个有效的 C 程序吗?

c - 可恢复处理器故障