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

时间:2012-11-21 19:00:24

标签: c visual-studio-2010 io

我有以下代码来检查常用单词字典的输入,并检查输入是否与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

1 个答案:

答案 0 :(得分:3)

fgets()将新行字符(如果遇到)写入正在填充的缓冲区中。在使用strcmp()

之前将其删除
char* new_line = strrchr(fileString, '\n');
if (new_line) *new_line = 0;

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

scanf("%30s", userString);

当在文件中找到字符串时,没有理由继续从break搜索文件的剩余部分while以避免不必要的处理。请注意,iFound的值永远不会在checkWordInFile()内更改,也不会用作返回值:始终返回0。我认为你在循环中意味着iFound = gC_FOUND;。您还定义了宏以指示找到但未找到但不在函数中使用这些宏,但使用硬编码值。

相关问题