Search code examples
cnewlinec-stringsfgetsstrcmp

If statement being skipped inside while loop


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?


Solution

  • 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 )