gpt4 book ai didi

C 输入检查和先前的输出验证码

转载 作者:太空宇宙 更新时间:2023-11-04 02:11:27 25 4
gpt4 key购买 nike

我有下面这段代码来检查输入是否与常用词词典相匹配,并检查输入是否与存储在 passHistory 文件中的先前输入匹配。我的问题是在 C 中比较字符串的 strcmp 方法似乎不存在在我的代码中正确执行,因为如果使用的常用词或输入已在 passHistory 中使用,它无法显示适当的错误。

一些指导将不胜感激。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

#define MAX 30
#define gC_FOUND 99
#define gC_NOT_FOUND -99


int checkWordInFile(char * fileName,char * theWord);



int main()
{

char userString[MAX + 1];

int iResult;

printf("Enter your string: ");
gets(userString);


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




if( iResult == gC_FOUND )
{
printf("\nFound your word in the dictionary");
}
else
{
printf("\nCould not find your word in the dictionary");
}

iResult = checkWordInFile("passHistory.txt",userString);
if( iResult == gC_FOUND )
{
printf("\nPassword used");
}
else
{
printf("\nOk to use!");
}

printf("\n\n\n");
system("pause");

} /* end of main */

int checkWordInFile(char * fileName,char * theWord){

FILE * fptr;
char fileString[MAX + 1];
int iFound = -99;
//open the file
fptr = fopen(fileName, "r");
if (fptr == NULL)
{
printf("\nNo dictionary file\n");
printf("\n\n\n");
system("pause");
return (0); // just exit the program
}

/* read the contents of the file */
while( fgets(fileString, MAX, fptr) )
{
if( 0 == strcmp(theWord, fileString) )
{
iFound = -99;
}
}

fclose(fptr);

return(0);



}//end of checkwORDiNFile

最佳答案

fgets()将换行符(如果遇到)写入它正在填充的缓冲区。在使用 strcmp() 之前删除它:

char* new_line = strrchr(fileString, '\n');
if (new_line) *new_line = 0;

请注意 gets()是一个危险的 api,因为没有对输入进行边界检查,可能会导致缓冲区溢出。一种更安全的读取用户输入的机制是 fgets()scanf()使用 %Ns 说明符,其中 N 指定要读取的最大字符数,N 必须比要读取的数组大小小一允许空终止符:

scanf("%30s", userString);

当在文件中找到字符串时,没有理由继续搜索文件的剩余部分,从 while break 避免不必要的处理。请注意,iFound 的值在 checkWordInFile() 中永远不会更改,并且不会用作返回值:始终返回 0。我想你的意思是 iFound = gC_FOUND; 在循环中。您还定义了宏来指示已找到和未找到,但不要在函数中使用它们,而是使用硬编码值。

关于C 输入检查和先前的输出验证码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13500219/

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