gpt4 book ai didi

c - 如何在 C 中使用 strcmp 将用户输入与文本文件进行比较?

转载 作者:太空宇宙 更新时间:2023-11-04 04:27:54 26 4
gpt4 key购买 nike

我在 C 中比较两个相同的字符串时遇到问题。使用方法 strcmp(),在比较文本文件中的一行与用户输入时似乎出现问题。为什么即使用户输入与文本文件相同,strcmp() 也会返回 -1。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Person{
char fName[10];
char lName[10];
};

char inputUser[10];

int main()
{
FILE *file;
int ret;
char data[20];

file = fopen("file.txt", "r");
struct Person *p1 = malloc(sizeof(struct Person));
gets(inputUser);

strcpy(p1->fName , inputUser);
struct Person *p2 = malloc(sizeof(struct Person));

while (fgets(data , 20 , file) != NULL){
strcpy(p2->fName , data);
ret = strcmp(p1->fName, p2->fName);
printf("\t%d\t%s\t%s\n", ret , p1->fName, p2->fName);
}
fclose(file);
file = fopen("file.txt","a");
fprintf(file, "%s\n", p1->fName);
fclose(file);

}

最佳答案

在您的 gets(inputUser) 之后添加:

inputUser[strlen(inputUser)-1] = '\0';

这将删除字符串的最后一个字符。 gets() 记录用户输入的换行符(回车键)。这就是为什么 strcmp() 认为它们不是同一件事,因为有换行符。

此外,为了避免段错误,您应该将 gets(inputUser) 更改为:

fgets(inputUser, sizeof(inputUser), stdin);

除了第二个参数限制了可以读取的数据长度外,这做同样的事情。使用 gets(),如果您输入超过 10 个字符以存储在 10 个字符的字符串中,它将出现段错误。

关于c - 如何在 C 中使用 strcmp 将用户输入与文本文件进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39693465/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com