I'm strugling with strcmp in c
i'm struggling to compare user input with the file contents. Basically i created a function that updates employee details that first prompts for the name of the employee and then it compares the name entered with those in the file. I tried doing this:
void update(EMPLOYEE *details)
{
FILE *file;
char search;
file = fopen("employees.txt","r");
if(file == NULL)
{
printf("File error!!!");
exit(0);
}
else
{
search = getc(file);
printf("Enter name: ");
scanf("%s",details->name);
if((strcmp(search,details->name) == 0))
{
printf("%s\n",details->name);
printf开发者_运维技巧("%d",details->employeeNumber);
}
}
fclose(file);
}
You are comparing a single character, search
with (I assume) an entire string, details->name
.
The method signature for strcmp
is:
int strcmp (const char *str1, const char *str2);
You are calling it as:
int strcmp (const char str1, const char *str2);
Not only this, but you are going to read past your str1 character buffer if you fix it to make it compile unless it happens to be character 0, which it won't be.
To fix this, you must do one of the following:
- Change your comparison to look at just the first characters.
- Change your search variable to be a string (probably char[]) and read in an entire string, then compare.
strcmp
takes a string (char *
) not a single letter. As others have mentioned in the comments, you need to update the getc
process to read more than the single letter.
a hint:
EMPLOYEE fileData;
while ( fread( &fileData, sizeof( fileData ), 1, file ) == sizeof( fileData )
{
...
}
EDIT: changed read to fread since it is a FILE*
hth
精彩评论