【发布时间】:2015-05-30 06:47:28
【问题描述】:
我正在编写一个代码来检查一个文档 (text1.txt) 中是否包含禁用词列表 (bannedwords.txt)。
例如,text1 文档包含一首歌的歌词,我想检查被禁止文档中的单词 pig 是否包含在其中。然后我希望输出类似于:
"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");
}
【问题讨论】:
-
我们喜欢明确的问题。 “但似乎无法将禁用词数组放入搜索中”甚至是什么意思?请给出一些简短的输入文件和输出的清晰示例,有什么问题以及您不明白为什么会发生这种情况。
-
提示:
push_back()到std::vector<std::string> bannedWords;而不是使用固定大小的数组,并在if/for构造函数之外创建bannedWords- 否则它将离开范围并被销毁在你想使用它之前。将其作为额外参数传递给CheckWord。在出现不可恢复的错误后,请致电exit(EXIT_FAILURE);而不是打印错误消息并尝试继续处理错误数据。使用while (getline(Myfile, line),不要测试while (...eof)。 -
您的问题是:“如何更改对 CheckWord 的调用以传递字符串数组?”。
标签: c++ arrays file search comparison