gpt4 book ai didi

c - 在文件中搜索字符串

转载 作者:行者123 更新时间:2023-12-04 05:22:43 25 4
gpt4 key购买 nike

我必须在文件中搜索输入的字符串,但下面的代码不起作用。总是说“在字典中找不到。文件(名为 Dictionary.txt)的内容如下:

pow
jaw
pa$$word

代码是:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX 30

main()
{
char inPassword[MAX + 1];
printf("\nEnter a password: ");
gets(inPassword);

printf("\n\nYou entered: %s, please wait, checking in dictionary.\n\n",inPassword);
checkWordInFile("Dictionary.txt",inPassword);

printf("\n\n\n");
system("pause");
}//end of main


void checkWordInFile(char *fileName, char *password);
{
char readString[MAX + 1];
FILE *fPtr;
int iFound = -1;
//open the file
fPtr = fopen(fileName, "r");

if (fPtr == NULL)
{
printf("\nNo dictionary file\n");
printf("\n\n\n");
system("pause");
exit(0); // just exit the program
}


while(fgets(readString, MAX, fPtr))
{
if(strcmp(password, readString) == 0)
{
iFound = 1;
}

}

fclose(fPtr);

if( iFound > 0 )
{
printf("\nFound your word in the dictionary");
}
else
{
printf("\nCould not find your word in the dictionary");
}


}

最佳答案

fgets() 将\n 留在字符串的末尾,除非 EOF。这修复了它:

while(fgets(readString, MAX, fPtr))
{
size_t ln = strlen(readString);
if (ln && readString[ln-1] == '\n') { readString[ln-1] = 0; --ln; }
if(ln && strcmp(password, readString) == 0)
{
iFound = 1;
}

}

关于c - 在文件中搜索字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13542694/

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