gpt4 book ai didi

C : Comparing 2 Strings

转载 作者:行者123 更新时间:2023-11-30 19:56:39 25 4
gpt4 key购买 nike

我必须比较 2 个字符串,一个来自文件,一个来自用户输入,这是文件:

Password 
abcdefg
Star_wars
jedi
Weapon
Planet
long
nail
car
fast
cover
machine
My_little
Alone
Love
Ghast

从行获取字符串的代码很好,但是比较两个字符串的代码没有给出正确的输出

int main(void){
int loop, line;
char str[512];
char string[512];
FILE *fd = fopen("Student Passwords.txt", "r");
if (fd == NULL) {
printf("Failed to open file\n");
return -1;
}
printf("Enter the string: ");
scanf("%s",string);
printf("Enter the line number to read : ");
scanf("%d", &line);

for(loop = 0;loop<line;++loop){
fgets(str, sizeof(str), fd);
}
printf("\nLine %d: %s\n", line, str);

if(strcmp(string,str) == 0 ){
printf("Match");
}else{
printf("No Match");
}
fclose(fd);
getch();
return 0;
}

也许 str 重置了,但我不知道,也许这里一些有才华的程序员可以看到问题。

有人知道我的字符串比较有什么问题吗?

正确输出:输入:jedi, 4 输出:Match

编辑:两个字符串相同,大小写相同编辑:dreamlax 修复了这个问题。

最佳答案

fgets() 读取后不会丢弃任何换行符,因此它会成为 str 的一部分,这会导致比较失败,因为 string 不会有换行符。要解决这个问题,您只需从 str 中删除换行符即可。

str[strlen(str) - 1] = '\0';
if (strcmp(string, str) == 0)
// ...

理想情况下,首先确保 strlen(str) > 0,否则您将调用未定义的行为。

关于C : Comparing 2 Strings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21431031/

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