Search code examples
cstringiostrcmp

How to compare user input with text file using strcmp in C?


I have a problem when comparing two of the same strings in C. Using the method strcmp(), there seems to be a problem when comparing a line from a text file to the user input. Why does strcmp() return -1 even if user input is identical to the text file.

#include <stdio.h>
#include <stdlib.h>  
#include <string.h>

struct Person{
    char fName[10];
    char lName[10];
};

char inputUser[10]; 

int main()
{   
   FILE *file;
   int ret;
   char data[20];

   file = fopen("file.txt", "r");
   struct Person *p1 =  malloc(sizeof(struct Person));
   gets(inputUser);

   strcpy(p1->fName , inputUser);
   struct Person *p2 =  malloc(sizeof(struct Person));

   while (fgets(data , 20 , file) != NULL){
      strcpy(p2->fName , data);
      ret = strcmp(p1->fName, p2->fName);
      printf("\t%d\t%s\t%s\n", ret , p1->fName, p2->fName);
   }
   fclose(file);
   file = fopen("file.txt","a"); 
   fprintf(file, "%s\n", p1->fName);  
   fclose(file);

}

Solution

  • Add this after your gets(inputUser):

    inputUser[strlen(inputUser)-1] = '\0';
    

    That will remove the last character of the string. gets() records the newline (Enter key) the user inputs. That's why strcmp() doesn't think they're the same thing, because of the newline.

    Also, to avoid a Segmentation Fault, you should change gets(inputUser) to:

    fgets(inputUser, sizeof(inputUser), stdin);
    

    This does the same thing except the second argument limits the length of the data that can be read. With gets(), if you enter over 10 characters to be stored in a 10-character string it will seg-fault.