2012-02-22 24 views
0

我正在搜索文本文件並在標題之後提取數據。但是,我有一些迭代器問題,我不知道如何克服。查找並提取文本文件中的數據

這是一個示例文本文件:

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返回的std ::向量, 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 ::搜索是一個曖昧的電話,我將如何去解決這個?
  • ifs.seekg(iit)不合法,我將如何着手使iit成爲一個有效的參數?

感謝。

+0

是頭部和數據始終在單獨的行?數據是否與您所示樣本中的單獨行有關?數據量總是一樣的,或者你如何跟蹤它的數量? – 2012-02-22 07:48:48

+0

如果數據來自二維數組,則與上述完全相同。要計算下載量,我必須在標題名稱和「\ n \ n」之間閱讀。數據後,總是有兩個\ n。 – 2012-02-22 09:12:43

回答

1

嗯,我覺得你的參數傳遞給標準::搜索問題

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)

+0

感謝您的回覆。你知道我可以如何設置iit指向的字符的偏移量嗎? – 2012-02-22 10:43:40

+0

@ user968243'iit'是istream的緩衝迭代這需要從'istream'的緩衝區的字節數內(所以當你提前通過''name.size(iit')+ 1'讀取從'istream'多字節的緩衝區),它實際上沒有任何位置。從看到你的代碼,我可以說'iit'通過'name.size()+ 1'得到了提升(所以它現在在'name.size()+ 1'的字節處),所以你可以執行'ifs.seekg name.size()+ 1)'。 – 2012-02-22 11:32:30

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