在文本文件c++中搜索短语
Searching for a phrase in a text file c++
我正在尝试读取一个文本文件,以查找短语/句子(/substring?)出现的次数。我目前已经对它做了大量的工作(见下面的代码),但正如你所看到的,它依赖于一些相当笨拙的if语句。
我无法访问我将在家里使用的文件,所以我使用了一个名为big.txt的文件,暂时搜索"answers"之类的短语。
理想情况下,我希望能够搜索"此错误代码1",并返回它发生的次数。任何关于如何让我的代码以这种方式工作的想法都将非常有用!
int fileSearch(string errorNameOne, string errorNameTwo, string textFile) {
string output; //variable that will store word from text file
ifstream inFile;
inFile.open(textFile); //open the selected text file
if (!inFile.is_open()) {
cerr << "The file cannot be opened";
exit(1);
}
if (inFile.is_open()) { //Check to make sure the file has opened correctly
while (!inFile.eof()) { //While the file is NOT at the end of the file
inFile >> output; //Send the data from the file to "output" as a string
if (output == errorNameOne) { //Check to look for first word of error code
marker = 1; //If this word is present, set a marker to 1
}
else if (marker == 1) { //If the marker is set to 1,
if (output == errorNameTwo) { //and if the word matches the second error code...
count++; //increse count
}
marker = 0; //either way, set marker to 0 again
}
}
}
inFile.close(); //Close the opened file
return count; //Function returns count of error
}
假设你的短语每行只能出现一次,并且数字在短语后面有几个空格,你可以逐行读取文件,并使用std::string::find()查看你的短语在行中的某个地方。这将返回短语的位置。然后,您可以在短语后面立即检查行的其余部分,以测试数字是否为1或0。
这段代码可能不是你想要的(仍然不确定确切的规格),但希望它应该包含足够多的例子,说明你可以做些什么来实现你的目标。
// pass the open file stream in to this function along with the
// phrase you are looking for and the number to check
int count(std::istream& is, const std::string& phrase, const int value)
{
int count = 0;
std::string line;
while(std::getline(is, line)) // read the stream line by line
{
// check if the phrase appears somewhere in the line (pos)
std::string::size_type pos = line.find(phrase);
if(pos != std::string::npos) // phrase found pos = position of phrase beginning
{
// turn the part of the line after the phrase into an input-stream
std::istringstream iss(line.substr(pos + phrase.size()));
// attempt to read a number and check if the number is what we want
int v;
if(iss >> v && v == value)
++count;
}
}
return count;
}
int main()
{
const std::string file = "tmp.txt";
std::ifstream ifs(file);
if(!ifs.is_open())
{
std::cerr << "ERROR: Unable to open file: " << file << 'n';
return -1;
}
std::cout << "count: " << count(ifs, "Header Tangs Present", 1) << 'n';
}
希望这能有所帮助。
相关文章:
- 有根的二进制搜索树.保留与其父级的链接
- 在C++中搜索嵌套多映射值
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 二进制搜索树叶数问题
- 为什么二进制搜索在我的测试中不起作用
- 正在尝试重载二进制搜索树分配运算符
- c++binary_search函数排序数组(流行名称搜索)出现问题
- 向量上的线性搜索
- 如何在动态数组上使用搜索函数
- 对于MacOS上的G++,如何添加默认的include目录/usr/local/include和默认的库搜索路径/usr
- cmake:添加要搜索头文件的目录
- 使用C++创建特殊的二叉搜索树
- 在C++的字符串中搜索和删除某些字符
- std::unordered_map 搜索算法是如何实现的?
- 使用不变量来确定二分搜索中的边界条件
- 二叉搜索如何比线性搜索更快?
- C 在使用UCS-2 LE编码的文件中搜索短语
- 如何有效地在元素之前和之后搜索关键短语
- 在文本文件c++中搜索短语
- 在C++中存储和搜索短语的最佳数据结构