是的,我有一个程序可以找到文件中的字符串位置及其所属的行。现在查找工作正常,但字符串比较有一个大问题,我无法理解,这是代码:
#include <stdio.h>
#include <conio.h>
#include <string.h>
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);
str[strlen(str)-1] = '\0';
if(strcmp(string,str) == 0 )
{
printf("Match");
}
else
{
printf("Nope");
}
fclose(fd);
getch();
return 0;
}
有人告诉我使用 strlen,我当然将其插入到代码中,但我认为这只会让情况变得更糟,我不知道现在该怎么办,我可以得到一些帮助吗?
文本文件:
Password
abcdefg
Star_wars
jedi
Weapon
Planet
long
nail
car
fast
cover
machine
My_little
Alone
Love
Ghast
谢谢 编辑:输入:随机单词,输入:行号。程序将转到所选行并扫描存储在那里的字符串,并将其与输入字符串进行比较。输出:匹配或否。
编辑:输入:密码,1 输出:匹配,输入:密码,2 输出:否。
最佳答案
你的程序对我来说工作得很好,除了你的文本文件在一些单词后面有尾随空格。但您的用户输入没有空格。尝试打印用户输入和读取行的长度,您就可以找到答案。
从文本文件中删除所有尾随空格,应该不会有任何问题。
正如其他人所提到的,最好在代码中使用类似的输入函数。您也可以使用 fgets
进行用户输入。
关于C 编程比较文件中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21452945/