首页 > 解决方案 > 将用户输入与文件中的文本进行比较

问题描述

下面的代码可以输出我文件中的内容。我试图找到一种方法来比较用户输入的单词/字符是否包含在文本文件中。例如,如果用户写“r”,那么程序会在文件中找到所有带有“r”的单词并输出它们。在那之后,我想用一些东西替换这个词,所以不是“r”,而是“k”。例如,“roadtrip”-->“koadtrip”。

文本文件一行一行的文字很多,一小部分截图在此处输入图像描述

#define MAX 1024
int main() {


 FILE* myFile = fopen("C:\\Users\\Luther\\Desktop\\txtfiles\\words.txt", "r+");
    char inputWord[MAX];
    char lineBuffer[MAX];
if (myFile1 == NULL)
{


printf("File Does Not Exist \n");
        return 1;
}

printf("Enter the word \n");
fgets(inputWord, MAX, stdin);
while (!feof(myFile1))
{
    char lineBuffer[1024];
    fscanf(myFile1, "%1024[^\n]\n", lineBuffer);
    //printf("%s\n", lineBuffer);
    while (fgets(lineBuffer, MAX, myFile)) {
        if (strstr(lineBuffer, inputWord))
            puts(lineBuffer);


    }
}   

}

我已经设法让它工作,现在程序输出有关用户输入的信息。如果在文本文件中找到相同的单词或其中的一部分,则打印该单词。看下面的截图:

现在我正在寻找一种方法来替换这个词。例如,在这种特定情况下,用户输入的单词是“es”,然后打印所有包含“es”的单词。有没有一种方法可以在所有情况下替换“es”并使其变为“er”。然后将更改保存在另一个文件中,而不更改原始文件中的任何内容。 在此处输入图像描述

标签: c

解决方案


其他一些起点

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<regex.h>
#include<sys/types.h>

int main (){
    //open file
    FILE *file_pointer = fopen("./test_txt.txt", "r");
    const char* search_for = "3_hau_gbs";

    int line_number = 1;
    char* line = NULL;
    size_t len = 0;


    regex_t regex;
    int failed = regcomp(&regex, search_for, REG_EXTENDED);
    //You are serching bitwise, so you must first semicompile it
    if(failed){
        regfree(&regex);
    } else {
        while(getline(&line, &len, file_pointer) != -1){
            //go line after line and check if it include the word you 
            //you are looking for
            int match = regexec(&regex, line, 0, NULL, 0);
            if(!match){
                //when find so output
                printf("%d:%s",line_number, line);
            }
            line_number++;
        }
        if(line){
            free(line);
        }
        regfree(&regex);
        fclose(file_pointer);
    }
  }

推荐阅读