I have this function named CheckEmployee. It opens a text file and check if the id the user entered exists in the record:
void CheckEmployee()
{
system("CLS");
char empID[5];
printf("Key in Employee ID: ");
scanf("%s", &empID);
FILE *fp = fopen("Employees.txt", "r");
char lineOfText[40];
while (fgets(lineOfText, 40, fp))
{
char id[6];
strncpy(id, lineOfText, 5);
id[5] = 0;
if (id == empID)
{
printf("Hello?");
}
}
fclose(fp);
}
The texfile contains the following:
E0001de Guzman, Franz Miguel C.
E0002de Guzman, Fernan Ralph C.
with 40 characters each line including white spaces. The problem is:
while
loops 4 times.(Should be twice only since there is only 2 records to traverse.)if (id == empID)
. But when I replaced it with if (strcmp(id, empID) == 0)
, the answer is false.UPDATE: strcmp
is now working. thanks to @barak manos. The while
looping 4 times still persists, but I get the result that I want.
To begin with, the char empID[5]
and char id[6]
look suspiciously short for your input.
Second, the value of expression id == empID
is always false, since you are essentially comparing memory addresses of two statically allocated arrays.
The expression strcmp(id,empID) == 0
should yield the result you're looking for, assuming that the id
and empID
arrays are sufficiently large to store the text that you are reading into them.
Keep in mind that string routines such as strcmp
, strcpy
, strlen
, printf
expect null-terminated strings as input. So you have to make sure that each char
array used for that purpose is large enough to store the input text plus an additional \0
character.