检查一个文档是否包含另一个c++的内容

Checking if one document has the contents of the other c++

本文关键字:另一个 包含 c++ 是否 文档 一个 检查      更新时间:2023-10-16

我正在写一个代码来检查一个文档(text1.txt)中是否包含禁止单词列表(bannedwords.txt)。

例如,text1文档包含一首歌的歌词,我想检查被禁止文档中的单词pig是否包含在其中。然后我希望输出类似于:

"pig" found 0 times
"ant" found 3 times

这就是我到目前为止所想到的,但似乎无法将一系列被禁止的单词放入搜索中。任何帮助都将是惊人的:D

感谢Fitz

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
bool CheckWord(char* filename, char* search)
{
    int offset;
    string line;
    ifstream Myfile;
    Myfile.open(filename);
    if (Myfile.is_open())
    {
        while (!Myfile.eof())
        {
            getline(Myfile, line);
            if ((offset = line.find(search, 0)) != string::npos)
            {
                cout << "The Word  " << search<< " was found" << endl;
                return true;
            }
            else
            {
                cout << "Not found";
            }
        }
        Myfile.close();
    }
    else
        cout << "Unable to open this file." << endl;
    return false;
}
int main()
{
    ifstream file("banned.txt");
    if (file.is_open())//file is opened
    {
        string bannedWords[8];//array is created
        for (int i = 0; i < 8; ++i)
        {
            file >> bannedWords[i];
        }
    }
    else //file could not be opened
    {
        cout << "File could not be opened." << endl;
    }
    ifstream text1;//file is opened
    text1.open("text1.txt");
    if (!text1)//if file could not be opened
    {
        cout << "Unable to open file" << endl;
    }
    CheckWord("text1.txt", "cat");
    system("pause");
}

您的main()函数正在将banned.txt的内容读取到名为bannedWords的8个std::string的数组中。

在那之后的任何地方都不会使用数组bannedWords。C++不能神奇地工作,编译器也不是通灵的,所以不能读懂你的想法来理解你想让代码做什么。如果一个数组(或其元素)在任何地方都不能访问,它们就不会被用来做你想用它们做的事。

您需要将字符串从bannedWords数组传递到CheckWord()。例如

 CheckWord("text1.txt", bannedWords[0].c_str());

将尝试将CCD_ 8中的第一个字符串的内容传递给CCD_。

但是,除非使CheckWord()的第二个参数(名为search)为const限定参数,否则这两个参数都不会编译。

或者,更好的是,将第二个参数的类型更改为std::string类型。如果你这样做,你就可以在上面消除c_str()的使用。

我并不认为这是你问题的完整解决方案,因为你的代码中有很多问题,有些与你所询问的内容有关,有些则不然。然而,我的建议会让你开始。

你的问题真的很模糊;看起来你需要花一些时间来确定你的程序结构,然后才能在这里寻求帮助
然而,由于我们都是新手,这里有一个合适的结构建议:(我省略了文件处理位,因为它们与基本结构无关)

//Populate your array of banned words
std::string bannedWords[8];
int i;
for (int i = 0; i < 8; ++i)
{
    file >> bannedWords[i];
}
//Load the entire file content into memory
std::ifstream in("text1.txt");
std::string fileContents((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());

因此,现在整个文件内容都在字符串"fileContents"中,8个被禁止的单词在"bannedWords"中。我建议使用这种方法,因为否则你会打开、阅读和关闭每个单词的文件。几乎不是一个好的设计。

现在,您必须对照文件内容检查每个单词。有一些更复杂的方法可以做到这一点,但最简单的选择是循环。

//Loop through each banned word, and check if it's in the file
for (int i = 0; i < 8; i++)
{
    if (fileContents.find(bannedwords[i]) != std::string::npos)
    {
        //Do whatever
    }    
}

显然,如果你想统计出现的次数,你需要用不同的方法来寻找,但这是另一个问题。