[英]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.
基本上我创建了一个 function 更新员工详细信息,首先提示输入员工姓名,然后将输入的姓名与文件中的姓名进行比较。 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
.您正在比较单个字符,
search
(我假设)整个字符串details->name
。
The method signature for strcmp
is: strcmp
的方法签名是:
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.不仅如此,如果你修复它以使其编译,你将读取你的 str1 字符缓冲区,除非它恰好是字符 0,它不会是。
To fix this, you must do one of the following:要解决此问题,您必须执行以下操作之一:
strcmp
takes a string ( char *
) not a single letter. strcmp
接受一个字符串( char *
)而不是一个字母。 As others have mentioned in the comments, you need to update the getc
process to read more than the single letter.正如其他人在评论中提到的那样,您需要更新
getc
进程以读取多个字母。
a hint:一个提示:
EMPLOYEE fileData;
while ( fread( &fileData, sizeof( fileData ), 1, file ) == sizeof( fileData )
{
...
}
EDIT: changed read to fread since it is a FILE*编辑:将 read 更改为 fread,因为它是 FILE*
hth hth
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.