2013-10-12 28 views
1

我目前有問題,試圖使用結構從文本文件中提取數據,然後將其存儲到向量中。但無論一疊我,除非我改變浮子的價值觀,詮釋爲字符串,它總是給我的錯誤是這樣的:從文本文件中將數據拖入結構中

MissionPlan.cpp:190: error: invalid conversion from ‘void*’ to ‘char**’
MissionPlan.cpp:190: error: cannot convert ‘float’ to ‘size_t*’ for argument ‘2’ to ‘__ssize_t getline(char**, size_t*, FILE*)

這是我的結構:

struct CivIndexDB { 
float civInd; 
int x; 
int y; 
} 

這是我的例如文本文件:

3.2341:2:3
1.5234:3:4

這是我用於提取從文本文件的數據,然後將其存儲到載體的代碼:

string line = ""; 
while (getline(civIndexFile,line)) { 
    stringstream linestream(line); 

    getline(linestream,civDb.civInd,':'); 
    getline(linestream,civDb.x,':'); 
    getline(linestream,civDb.y); 
    civIndexesList.push_back(civDb);    
} 

將結構中的變量類型更改爲字符串並不是我在應用程序中稍後需要的,我需要根據其浮點值對向量值進行排序。

我感謝任何幫助。謝謝!

+0

爲什麼不使用二進制文件?我不記得如何編寫二進制文件,但我認爲在你的例子中它們更合適。 – MRB

+1

您可以隨時讀取字符串,然後將字符串轉換爲您的結構中需要的數字。但我認爲P0W的答案是最簡單的。 – john

+0

@john如果結構變量是字符串類型,那麼存儲在向量中的數據必須是字符串類型。即使我將字符串轉換爲我需要的類型,我仍然需要一個能夠存儲float,int,int(我認爲這是不可能的)的向量,並在稍後進行排序。 –

回答

3

沒有尋找到您的具體問題/錯誤,我建議,如果文件格式是固定的簡單的方法是:

char ch; // For ':' 
while (civIndexFile >> civDb.civInd >> ch >> civDb.x >> ch >> civDb.y) 
{ 
    civIndexesList.push_back(civDb); 
} 

編輯

有關浮點值進行排序,你可以重載<運營商:

struct CivIndexDB { 
    float civInd; 
    int x; 
    int y; 

    bool operator <(const CivIndexDB& db) const 
    { 
    return db.civInd > civInd; 
    } 
}; 

然後用std::sort

std::sort(civIndexesList.begin(), civIndexesList.end());

+0

似乎更改文件格式是我現在最好的選擇。但是,你能告訴我二進制和文本模式文件的區別嗎?我閱讀了在線資源,我並不真正瞭解它們。 –

+0

@JoelSeah你爲什麼要改變文件格式,'float:int:int'可以和上面的代碼完全一致。試試[這](http://pastebin.com/6vhiVH6U)代碼,更改文件名 – P0W

+0

你沒有問我把文件從文本更改爲二進制文件,然後使用上面的代碼來測試它? –

0

這個怎麼樣?

#include <vector> 
#include <cstdlib> 
#include <sstream> 
#include <string> 
#include <fstream> 
#include <iostream> 

struct CivIndexDB { 
    float civInd; 
    int x; 
    int y; 
}; 

int main() { 
    std::ifstream civIndexFile; 
    std::string filename = "data.dat"; 

    civIndexFile.open(filename.c_str(), std::ios::in); 

    std::vector<CivIndexDB> civ; 
    CivIndexDB cid; 

    if (civIndexFile.is_open()) { 
     std::string temp; 

     while(std::getline(civIndexFile, temp)) { 
      std::istringstream iss(temp); 
      int param = 0; 
      int x=0, y=0; 
      float id = 0; 

      while(std::getline(iss, temp, ':')) { 
       std::istringstream ist(temp); 
       if (param == 0) { 
        (ist >> id) ? cid.civInd = id : cid.civInd = 0; 
       } 
       else if (param == 1) { 
        (ist >> x) ? cid.x = x : cid.x = 0; 
       } 
       else if (param == 2) { 
        (ist >> y) ? cid.y = y : cid.y = 0; 
       } 
       ++param; 
      } 
      civ.push_back(cid); 
     } 
    } 
    else { 
     std::cerr << "There was a problem opening the file!\n"; 
     exit(1); 
    } 

    for (int i = 0; i < civ.size(); ++i) { 
     cid = civ[i]; 
     std::cout << cid.civInd << " " << cid.x << " " << cid.y << std::endl; 
    } 

    return 0; 
}