首页 > 解决方案 > 如何使用文件中的整数搜索记录?

问题描述

目前,我只能使用字符串进行搜索,但当用户输入 12 位数字(long long 数据类型)时,我不知道如何搜索记录。我尝试在原始 if(strcmp(....) 代码所在的位置编写 if(identityC == line) 但我没有让它工作。有什么解决方案吗?

char line[255], name[30];
long long identityC;

FILE* fpointer = fopen("123 Hotel Customer.txt", "r");

//printf("\nPlease Enter Your Identity Card Number: ");
//scanf("%lld", &identityC);

printf("\nPlease Enter your Name to Search your Room Booking: ");
scanf("%s", &name);

while (!feof(fpointer))
{
    fgets(line, 255, fpointer);
    
    if (strncmp(name, line, strlen(name)) == 0)
        printf("%s", line);
} 

fclose(fpointer);

return;

标签: c

解决方案


注意:目的是展示一种开始使用文件的方法。

假设您以这种格式将信息存储在文件中,

roomno,Hotel Name,Customer name,isOccupied
datatype: int, string, string, bool

你可以这样做-

FILE* file = fopen("filename.txt","w");
char buffer[512];
while(fgets(buffer, 512, file)!=NULL){
  int roomNo = strtok(buffer, "\n,");
  char* hotel_name = strtok(NULL, "\n,");
  char* customer_name = strtok(NULL, "\n,");
  bool isOccupied = strtok(NULL, "\n,");
// Now you are done extracting values from file. Now do any work with them.
}

这是有关strtok()fgets()的信息。

另外,来自 Steve Summit,为什么 while (!feof (file) ) 总是错误的?


推荐阅读