簡體   English   中英

從文本文件中查找和提取數據

[英]Find and extract data from a text file

我正准備搜索文本文件並在標題后提取數據。 但是,迭代器存在一些我不知道如何克服的問題。

這是一個示例文本文件:

 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");命名為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有效?

謝謝。

好吧,我認為您對std :: search的參數有問題

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM