1

現在、構造体を使用してテキストファイルからデータを取得し、それをベクターに格納しようとして問題が発生しています。しかし、何をしても、float、int の値を文字列に変更しない限り、常に次のようなエラーが発生します。

MissionPlan.cpp:190: エラー: 'void*' から 'char**' への変換が無効です<br> MissionPlan.cpp:190: エラー: 引数 '2' から '__ssize_t' の 'float' を 'size_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);            
}

構造体の変数の型を文字列に変更する必要はありません。アプリケーションの後半で、float 値に基づいてベクトル値を並べ替える必要があるためです。

助けていただければ幸いです。ありがとう!

4

2 に答える 2

3

正確な問題/エラーを調べずに、ファイル形式が修正されている場合、最も簡単な方法は次のとおりです。

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

編集

float 値でソートするには、<operatorをオーバーロードできます。

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

于 2013-10-12T07:49:44.340 に答える
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;
}
于 2013-10-12T07:58:32.673 に答える