检查一个文档是否有其他C++的内容
我正在写一个代码来检查一个文档text1.txt是否包含一个禁止使用的单词列表bannedwords.txt 例如,text1文档包含一首歌曲的歌词,我想检查是否包含禁止文档中的单词pig。然后,我希望输出类似于:检查一个文档是否有其他C++的内容,c++,arrays,file,search,comparison,C++,Arrays,File,Search,Comparison,我正在写一个代码来检查一个文档text1.txt是否包含一个禁止使用的单词列表bannedwords.txt 例如,text1文档包含一首歌曲的歌词,我想检查是否包含禁止文档中的单词pig。然后,我希望输出类似于: "pig" found 0 times "ant" found 3 times 这是我到目前为止提出的,但似乎无法将一系列被禁止的单词放入搜索中。任何帮助都将是惊人的:D 谢谢菲茨 #include <iostream> #include <fstream>
"pig" found 0 times
"ant" found 3 times
这是我到目前为止提出的,但似乎无法将一系列被禁止的单词放入搜索中。任何帮助都将是惊人的:D
谢谢菲茨
#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");
}
您的主要功能是将banked.txt的内容读入一个由8个std::string组成的名为bannedWords的数组
此后任何地方都不会使用数组bannedWords。C++不需要魔法,编译器也不是心灵的,所以不能理解你的想法,以便理解你想要你的代码做什么。如果数组或其元素在任何地方都没有被访问,它们将不会被用来执行您想要的操作
您需要将字符串从bannedWords数组传递到CheckWord。比如,
CheckWord("text1.txt", bannedWords[0].c_str());
将尝试将BannedWord中第一个字符串的内容传递给CheckWord
但是,除非将名为search的CheckWord的第二个参数设置为const限定,否则也不会编译
或者,更好的方法是将第二个参数的类型更改为std::string类型。如果您这样做,您就可以在上面的示例中消除c_str的使用
我并不认为这是解决您的问题的一个完整的解决方案——因为您的代码中有许多问题,有些问题与您所问的有关,有些问题与您所问的无关。不过,我的建议会让你开始的。你的问题真的很模糊;看起来你需要花一些时间来确定你的程序结构,然后才能在这里寻求帮助。 然而,由于我们都是新人,这里有一个合适结构的建议: 我省略了文件处理部分,因为它们与基本结构无关 所以现在整个文件内容都在字符串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
}
}
显然,如果你想计算出现的次数,你需要做一些不同的查找,但这是另一个问题。我们喜欢清晰的问题。什么是但似乎不能将一系列被禁止的单词放入搜索中,甚至意味着什么?请给出一些简短输入文件和输出的清晰示例,说明错误和不理解的原因;而不是使用固定大小的数组,并在if/for构造函数之外创建bannedWords,否则它将离开作用域并在您想要使用它之前被销毁。将其作为额外参数传递给CheckWord。发生不可恢复的错误后,调用exitEXIT_FAILURE;而不是打印错误消息并尝试继续使用错误数据。使用while getlineMyfile、line和do not test for while…eof。您的问题是:如何更改对CheckWord的调用以传递字符串数组?。
//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
}
}