[英]How to compare user input with text file using strcmp in C?
我在比较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)
之后添加此项gets(inputUser)
:
inputUser[strlen(inputUser)-1] = '\0';
这将删除字符串的最后一个字符。 gets()
记录用户输入的换行符(Enter键)。 这就是为什么strcmp()
不认为它们是同一个东西,因为换行符。
另外,要避免分段错误,您应该将gets(inputUser)
更改为:
fgets(inputUser, sizeof(inputUser), stdin);
除了第二个参数限制可以读取的数据的长度之外,这也是一样的。 使用gets()
,如果输入超过10个字符以存储在10个字符的字符串中,则会出现seg-fault。
只需更换
strcpy(p2->fName , data);
ret = strcmp(p1->fName, p2->fName);
通过
strcpy(p2->fName , strtok(data, "\n"));
ret = !strcmp(p1->fName, p2->fName);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.