从文本文件中查找和提取数据

Find and extract data from a text file

本文关键字:提取 数据 查找 文本 文件      更新时间:2023-10-16

我正在字符串中搜索文本文件并提取标题后的数据。然而,我在迭代器方面遇到了一些问题,我不知道如何克服这些问题。

这是一个示例文本文件:

Relay States
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0

理想情况下,我想调用LoadData<bool> something.LoadData("Relay States");,并让它返回一个std::vector,带有{0,0,0,0,0,0,…}。

template<typename T> std::vector<T> CProfile::LoadData(const std::string& name)
{
    std::ifstream ifs(FILE_NAME);
    std::vector<T> data;
    std::istreambuf_iterator<char> iit = std::istreambuf_iterator<char>(ifs);
    std::search(iit, ifs.eof(), name.begin(), name.end());
    std::advance(iit, name.size() + 1);
    T buffer = 0;
    for(ifs.seekg(iit); ifs.peek() != 'n' && !ifs.eof(); data.push_back(ifs))
    {
        ifs >> buffer;
        data.push_back(buffer);
    }
    return data;
}

据我所知,我的代码的主要问题是:

  • std:搜索是一个模棱两可的调用,我该如何解决这个问题
  • 如果seekg(iit)不合法,我该如何使它成为一个有效的论点

谢谢。

我认为你对std::search的args是的问题

std::search(iit, ifs.eof(), name.begin(), name.end());

应该是

std::search(iit, std::istreambuf_iterator<char>(), name.begin(), name.end());

至于第行:for循环中的ifs.seekg(iit)并不好,因为seekg希望streampos类型的偏移量不是迭代器。所以它应该是ifs.seekg(0)

这样的东西怎么样:

template<typename T> std::vector<T> CProfile::RealLoadData(std::istream &is)
{
    std::string line;
    std::vector<T> data;
    while (std::getline(is, line))
    {
        if (line.empty())
            break;  // Empty line, end of data
        std::istringstream iss(line);
        T temp;
        while (iss >> temp)
            data.push_back(temp);
    }
    return data;
}
template<typename T> std::vector<T> CProfile::LoadData(const std::string& name)
{
    std::string line;
    std::ifstream ifs(FILE_NAME);
    while (std::getline(ifs, line))
    {
        if (line == name)
        {
            // Found the section, now get the actual data
            return RealLoadData<T>(ifs);
        }
    }
    // Section not found, return an empty vector
    return std::vector<T>();
}