0

I'm trying to take input from the user and compare it with a CSV file that contains only the same input that I'm trying to compare which is "gaber123".

For some reason, the output is "fail".

Here is the code

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


int main() {
    char x[20],data[20];

    scanf("%s",&x);
    FILE *fp= fopen("Accounts.csv","r");
    fgets(data,20,fp);
   

     int compare= strcmp(data, x);
    if(compare==0){
        printf("success!");

    }
    else{
        printf("fail");
    }
    return 0;
}
  • 3
    Don't forget that `fgets` keeps the newline (if any) in the input string. Please see [Removing trailing newline character from fgets() input](https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input/28462221#28462221) – Weather Vane Oct 25 '22 at 13:03
  • `scanf` used the way you do is pretty dangerous – especially as the array is so short. A user might easily provide too long input, provoking undefined behaviour for writing beyond array bounds this way. Safer is including the length in the format string, e.g. `scanf("%19s")` – note that the number indicates the maximum number of characters read, but as `%s` null-terminates you need to leave one byte extra for, thus the value smaller than size by one. – Aconcagua Oct 25 '22 at 13:07

0 Answers0