【问题标题】:How do I search a record using an integer from a file?如何使用文件中的整数搜索记录?
【发布时间】:2021-07-13 11:51:09
【问题描述】:

目前,我只能使用字符串搜索,但当用户输入 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;

【问题讨论】:

  • 请明确说明您希望您的代码做什么,以及什么不起作用。像现在这样,我们将无法为您提供帮助
  • 不是您的问题,但请参阅Why is while ( !feof (file) ) always wrong?
  • 文件123 Hotel Customer.txt在里面是什么样子的?客户姓名、身份证号等字段如何表示?
  • 我相信这可能是您的解决方案:stackoverflow.com/a/15757280/16397750
  • 通过使用strncmp,你会得到"Weather""WeatherVane..."之间的错误匹配。

标签: c


【解决方案1】:

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

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

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,Why is while (!feof (file) ) always wrong?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-19
    • 2019-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-29
    • 1970-01-01
    相关资源
    最近更新 更多