-1

I'm trying to use the following code to see if a certain name is in a file and if it is equal to the one entered by the user:

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

void main(){
    FILE *hash;
    hash = fopen("hash.txt","r");
    char name[100], line[100];
    char *user;
    int flag = 0;

    printf("Enter name: ");
    fgets(name, 100, stdin);

    if(hash == NULL){
        printf("Error opening file");
        exit(1);
    }
    while(fgets(line,100,hash)){
        user = strtok(line,":");
        if(strcmp(user,name)==0){
            flag = 1;
            printf("%d",flag);
            break;
        }
    } 
}

My problem is that the if statement is constantly being skipped. I added the flag to see if it runs and the printf() afterwards to print the flag but it isn't printing at all showing that the if statement isn't working. Anyone know why?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Overwatch
  • 19
  • 2
  • 1
    Presumably the `strcmp` never returns 0 - most likely because `name` includes a newline character (which `user` doesn't) – UnholySheep Jan 03 '23 at 10:44
  • After you input the user name in your "Enter name:" prompt, you probably hit the enter/return key. That character produced by the enter/return key gets stored in your name variable after your call to `fgets()` , make sure you deal with that (e.g. add some code to debug/inspect what is stored in your `name` variable, and add soem code to remove that character) – nos Jan 03 '23 at 10:45
  • 1
    Have you tried printing both `user` and `name` before the comparison? That should be the natural thing to do. – klutt Jan 03 '23 at 10:46

1 Answers1

1

The function fgets can store the new line character '\n' that corresponds to the pressed key Enter with the entered string. You should remove it as for example

fgets(name, 100, stdin);

name[ strcspn( name, "\n" ) ] = '\0';

Pay attention to that according to the C Standard the function main without parameters shall be declared like

int main( void )
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335