我正在与 c 中的 strcmp 作斗争
我正在努力将用户输入与文件内容进行比较。基本上,我创建了一个更新员工详细信息的函数,该函数首先提示输入员工的姓名,然后将输入的姓名与文件中的姓名进行比较。我尝试这样做:
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);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在将单个字符
search
与(我假设)整个字符串details->name
进行比较。strcmp
的方法签名是:调用它:
不仅如此,如果您修复它以使其编译,您将读取您的 str1 字符缓冲区,除非它碰巧是字符 0,但事实并非如此。
要解决此问题,您必须执行以下操作之一:
You are comparing a single character,
search
with (I assume) an entire string,details->name
.The method signature for
strcmp
is:You are calling it as:
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:
strcmp
采用字符串 (char *
),而不是单个字母。正如其他人在评论中提到的,您需要更新 getc 进程以读取多个字母。strcmp
takes a string (char *
) not a single letter. As others have mentioned in the comments, you need to update thegetc
process to read more than the single letter.提示:
编辑:将 read 更改为 fread,因为它是 FILE*
hth
a hint:
EDIT: changed read to fread since it is a FILE*
hth