2011-02-28 114 views
0

要使用我爲執行計算而編寫的代碼,我需要從外部文本文件讀入數據(數字和字符串),並將它們存儲在字符串或ints /雙打。我已經寫了一個模板函數來做到這一點。 CashCow,Howard Hinnant和wilhelmtell對以前的問題提供了幫助。C++:從外部文件讀取數據;我的代碼在代碼結束前停止讀取的問題

該函數似乎適用於整數/雙精度,但我有一個字符串數據的問題。

我需要從我的外部文件的一行數據進入一個向量,但函數讀取多行。這是我的意思。比方說,這是在外部文本文件(如下圖):


vectorOne //標識爲數據的子集爲一個矢量

「1」「2」「3」 //這些值應該進入一個向量,(vectorOne)

vectorTwo //用於數據的子集標識符另一載體(vectorTwo)

「4」「5」「6」 //這些值應進入一個不同的載體

vectorThree //標識符用於另一矢量數據的子集(vectorThree)

「7」「8」「9」 //這些值應進入一個不同的載體


如果我尋找一個數據子集標識符/標籤(如vectorOne),我只需要下一行的數據進入我的結果向量。問題是標識符/標籤下的所有數據都在結果向量中結束。所以,如果vectorTwo是我想要的,我期望我的結果向量包含元素「4,5,6」。但這一翻譯,它包含4至9在我的代碼(如下圖),我認爲行:

while (file.get() != '\n'); 

確保讀取將停止在一個換行符(即每一行數據後)。

對於出現什麼問題,我將非常感激。

下面的代碼(爲了清楚起見,我將其配置爲字符串):

#include <algorithm> 
#include <cctype>  
#include <istream> 
#include <fstream> 
#include <iostream>  
#include <vector> 
#include <string> 
#include <sstream> 
#include <iterator> 

using namespace std; 

template<typename T> 
void fileRead(std::vector<T>& results, const std::string& theFile, const std::string& findMe, T& temp) 
{ 
    std::ifstream file(theFile.c_str()); 
    std::string line; 

    while(std::getline(file, line)) 
    { 
     if(line == findMe) 
     { 
      do{ 
       std::getline(file, line, '\''); 
       std::getline(file, line, '\''); 

       std::istringstream myStream(line); 

       myStream >> temp; 
       results.push_back(temp); 
      } 
      while (file.get() != '\n'); 
     } 
    } 
} 


int main() 
{ 
    const std::string theFile    = "test.txt"; // Path to file 
    const std::string findMe    = "labelInFile"; 
    std::string temp; 

    std::vector<string> results; 

    fileRead<std::string>(results, theFile, findMe, temp); 

    cout << "Result: \n"; 
    std::copy(results.begin(), results.end(), std::ostream_iterator<string>(std::cout, "\n")); 

    return 0; 
} 

感謝

回答

1

看起來像你對我可能有問題混合getlineget

當您閱讀完所需矢量的名稱後,即可開始閱讀單引號之間的部分。一旦你閱讀了單引號之間的任何內容,就檢查下一個字符是否是行尾。如果換行之前還有其他內容,則測試失敗,並且它讀取下一對單引號之間的內容。如果在最後一個單引號之後的末尾或空格處有任何評論,您將會失敗。

嘗試將整行讀入一個字符串,然後將其讀取爲一個字符串流。那樣,你不能越過線的末尾。

+0

大衛,非常感謝!在我的外部文本文件中,我的行末沒有任何評論,但我有一個空間!我擺脫了空間,現在代碼按預期工作。我只是無法弄清楚爲什麼事情不起作用!非常感謝。 – user616199 2011-02-28 21:41:50