C编程比较文件中的字符串

时间:2014-01-30 09:50:19

标签: c file text

是的,所以我有一个程序,它会在文件中找到一个字符串,以及它所属的行。现在查找工作正常,但字符串比较有一个大问题,我无法理解,这里是代码:

#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输出:不。

1 个答案:

答案 0 :(得分:2)

你的程序对我来说很好,除了你的文本文件在一些单词之后有空格。但是您的用户输入没有空格。尝试打印用户输入和读取行的长度,你可以找到。

从文本文件中删除所有尾随空格,应该没有任何问题。

正如其他人所提到的,最好在代码中使用类似的输入函数。您也可以使用fgets进行用户输入。