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

时间:2012-02-22 07:36:16

标签: c++ algorithm search fstream

我要搜索文本文件并在标题后提取数据。但是,我遇到了一些我不知道如何克服的迭代器问题。

这是一个示例文本文件:

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");并让它返回一个带有{0,0,0,0,0,0,0,0,...}的std :: vector。

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 :: search是一个含糊不清的电话,我该如何解决这个问题?
  • ifs.seekg(iit)不合法,我怎样才能让iit成为有效的论据?

感谢。

2 个答案:

答案 0 :(得分:1)

嗯,我认为你对std :: search的争论是个问题

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

应该是

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

对于ifs.seekg(iit)循环中的行for并不好,因为seekg需要某种类型streampos的偏移而不是迭代器。所以它应该是ifs.seekg(0)

答案 1 :(得分:1)

这样的事情怎么样:

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>();
}