繁体   English   中英

无法正确比较文件中的字符串和用户输入

[英]Can't compare string in file and user input properly

我的任务如下:

  1. 在列表中添加一个顽皮的词
  2. 显示列表中的所有顽皮词
  3. 需要审查的输入句子

我需要将顽皮的词保存在一个文件中,并比较用户输入是否包含一个坏词,这样我就可以用星星来审查它。 我的问题是我似乎无法弄清楚为什么我将句子中的每个单词与“naughtyList.txt”进行比较的方法不起作用。 我在 OptionThree() 中的 strcmp 代码不适用于完整的句子。

这是我的 3 个功能:

void OptionOne() {
    char word[20];
    //"a" for continue writing in the same file, and not overwrite it
    FILE *list = fopen("naughtyList.txt", "a");                                                         
    
    printf("Enter new naughty word: ");
    scanf("%s", &word);
    
    fputs(word, list);
    fputs("\n", list);
    
    fclose(list);
}

void OptionTwo() {
    FILE *list = fopen("naughtyList.txt", "r");
    char word[20];
    
    if(list == NULL) {
        printf("Naughty words list does not exist, add some word in the list first\n");
    }else {
        printf("All naughty words in the list: \n");
        while(fgets(word, sizeof(word), list)) {
            printf("%s", word);
        }
    }
    
    fclose(list);
}

void OptionThree() {
    FILE *list = fopen("naughtyList.txt", "r");
    char word[20];
    
    char input[100];
    char eachWord[20][20];
    char *pointer;
    int i = 0;
    int count = 0;
    
    printf("Input your sentence: ");
    fflush(stdin);                                                                                      
    fgets(input, sizeof(input), stdin);
    
    //solution for getting each word in a string using strtok
    for(pointer = strtok(input, " "); pointer != NULL; pointer = strtok(NULL, " ")) {                   
        strcpy(eachWord[i], pointer);
        i++;
        count++;
    }

    for(i = 0; i < count; i++) {
        while(fgets(word, sizeof(word), list)) {
            word[strcspn(word, "\n")] = 0;  // remove tralling \n at the end of naughty word list when scaning file                                                         
            if(strcmp(eachWord[i], word) == 0) {
                printf("PING\n");
            }
        }
    }

    fclose(list);
}

这应该是“option3”所需的全部......我希望它具有教育意义......

char input[100];
printf( "Input your sentence: " );
fgets( input, sizeof(input), stdin );
input[ strlen( input ) - 1 ] = 0;

FILE *fp = fopen( "naughtyList.txt", "r" );
if( fp == NULL ) exit(0); // handle error...

char word[20];
while( fgets( word, sizeof( word ), fp ) ) {
    word[ strlen( word ) - 1 ] = 0;

    char *cp;
    while( ( cp = strstr( input, word ) ) != NULL )
        for( char *xp = word; *xp; xp++ )
            *cp++ = '#';
}
fclose( fp );

printf( "Clean: '%s'\n", input );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM