-2

Currently, I can only search using a string but I don't know how to search a record when the user inputs a 12 digit number (long long data type). I tried to write if(identityC == line) where the original if(strcmp(....) code was at but I didn't get it to work. Any solutions?

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;
  • 1
    Please clarify exactly what you want your code to do, and what isnt working. Like this right now, we wont be able to help you – Jakob Sachs Jul 13 '21 at 11:54
  • 3
    Not your question, but see [Why is `while ( !feof (file) )` always wrong?](https://stackoverflow.com/questions/5431941) – Steve Summit Jul 13 '21 at 11:57
  • You can always "print" the number to a string, then use the string as you already do. – pmg Jul 13 '21 at 11:58
  • 1
    What does the file `123 Hotel Customer.txt` look like inside? How are the customer name, identity card numbers, and other fields represented? – Steve Summit Jul 13 '21 at 11:59
  • 1
    I believe this might be your solution: https://stackoverflow.com/a/15757280/16397750 – ankit_acharya Jul 13 '21 at 12:04
  • `if (identityC == line)`: `identityC ` is a `long long` and `line` is an array of `char`. What makes you think that the comparision is valid? Didn't you get any compiler warnings? – Jabberwocky Jul 13 '21 at 12:13
  • 1
    By using `strncmp` you'll get a false match between say `"Weather"` and `"WeatherVane..."`. – Weather Vane Jul 13 '21 at 12:17

1 Answers1

0

Note: The purpose is to show a way to get started with working with files.

Assuming you store information in your file in this format,

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

you can do this-

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

Here is information on strtok() and fgets().

Also, from Steve Summit, Why is while (!feof (file) ) always wrong?

Daoist Paul
  • 133
  • 8