所以我有一个小问题。我正在做一项学校作业,但我不知道如何获得解决方案。因此,作业需要我读取二进制形式的文件,然后在该读取的文件中找到某些位序列。然后,我将打印出该序列的所有实例的找到序列中第一位的索引。
因此,如果我要编写一个二进制序列
10011001001011101
并搜索1001
序列,我将得到如下索引:0, 4
。现在,当我编写代码来对一串 1 和 0 执行此操作时,一切都很好,但是当我开始实现文件读取和搜索时,我遇到了问题。该文件是一个 .bmp,以二进制形式读取它应该会给我一个像素值字符串(不太确定如何检查该字符串是否确实是我认为的那样)。然后,当我去搜索二进制子字符串时,当有很多实例时,它找不到它的任何实例。我的程序返回 std::string::npos
并且不会循环遍历字符串。
这是我目前拥有的代码:
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <filesystem>
using namespace std;
void f(vector<size_t>& poz, string pattern, string filename) {
std::ifstream file(filename, std::ios::binary);
if (file)
{
file.seekg(0, std::ios::end);
std::streampos length = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<char> buffer(length);
file.read(&buffer[0], length);
std::stringstream localStream;
localStream.rdbuf()->pubsetbuf(&buffer[0], length);
string solution = localStream.str();
//after i get the full string i should be able to find the instances of my pattern
//this file contains only white pixels and red (000000000000000011111111) pixels
cout << "Pattern: " << pattern <<endl;
size_t index = solution.find(pattern);
cout << "First found pixel: " << index << endl; // this value is the exact same as npos
cout << "string::npos: " << string::npos;
while (index != string::npos) {
poz.push_back(index);
index = solution.find(pattern, index + pattern.size());
}
}
}
int main() {
vector<size_t> poz;
string file = "test.bmp";
string pattern = "000000000000000011111111"; //looking for red pixels only
f(poz, pattern, file);
for (auto i = poz.begin(); i != poz.end(); i++) {
if (i == (poz.end() - 1))
cout << *i << endl;
else
cout << *i << ", ";
}
}
我不知道我搜索的序列是否错误,或者我的文件是否实际上没有转换为二进制字符串,这就是搜索没有找到任何结果的原因。如有任何帮助,我们将不胜感激。
根据 @user4581301 的观察,我在解决方案之前读取的文件以字节形式传递,因此我无法找到我希望的匹配项。改变我阅读文件的方式解决了我的问题。我决定读取字符,然后将它们转换为位集数组,而不是以二进制模式读取文件并将其直接存储到字符串中。然后,我将位集数组连接成一个字符串,并使用
.find()
函数来查找我的出现情况。是的,这个过程很慢,但从技术上讲,按照我的问题是有效的。我的代码已更改以反映这一点。