use*_*362 -2 c structure strcmp
我必须比较2个字符串,一个来自文件,一个来自用户输入,这里是文件:
Password
abcdefg
Star_wars
jedi
Weapon
Planet
long
nail
car
fast
cover
machine
My_little
Alone
Love
Ghast
Run Code Online (Sandbox Code Playgroud)
从行中获取字符串的代码很好但是用于比较2个字符串的代码没有给出正确的输出
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;
}
Run Code Online (Sandbox Code Playgroud)
也许str重置但我不知道,也许这里有一些有才华的程序员可以看到问题.
有人知道我的字符串比较有什么问题吗?
正确输出:输入:jedi,4输出:匹配
编辑:两个字符串是相同的,在相同的情况下编辑:dreamlax修复此.
fgets()读取后不会丢弃任何换行符,因此它将成为其中的一部分str,这将导致比较失败,因为string不会有换行符.要解决这个问题,您只需要从中删除换行符str.
str[strlen(str) - 1] = '\0';
if (strcmp(string, str) == 0)
// ...
Run Code Online (Sandbox Code Playgroud)
理想情况下,strlen(str) > 0首先确保,否则您将调用未定义的行为.
| 归档时间: |
|
| 查看次数: |
139 次 |
| 最近记录: |