生のファイルを開き、データを読み取り、それをベクターに格納するこのコードを取得しました。今、私はJavaのバックグラウンドを持っており、いくつかの基本を読んだ後、C ++での動作が少しよく理解できたと感じていますが、ファイルリーダー関数の形式に出会ったことはありません...
目的は、関数で作成されたベクターに格納されているデータを取得し、CSVファイルに出力することです。Javaでは問題ありません。私が欲しいのは、C ++の完全な初心者である誰かを助けることができるいくつかのポインタといくつかの良いリソースです。繰り返しますが、私は答えではなく、ヒントを探しています。
//Set file name and path
std::string filename = "Betty.raw";
//Open binary file for reading
std::ifstream myfile(filename.c_str(), std::ios::in | std::ios::binary);
if (myfile.is_open()) {
unsigned char c = 0;
float f = 0;
//Loop through data X changes first/fastest.
for (unsigned int iz = 0; iz < mZMax; iz++)
for (unsigned int iy = 0; iy < mYMax; iy++)
for (unsigned int ix = 0; ix < mXMax; ix++) {
//Initialise empty vector
my::Vec3f vec = my::Vec3f();
//Read x then y then z and store in vec (vector)
//Data needs converting to float from char and adjusted
myfile.read((char *)&c, 1);
f = (float)c;
vec.x = f/255-0.5;
myfile.read((char *)&c, 1);
f = (float)c;
vec.y = f/255-0.5;
myfile.read((char *)&c, 1);
f = (float)c;
vec.z = f/255-0.5;
//Store vector in datastructure
mData[iz][iy][ix] = vec;
}
main() {
char delimiter = ", ";
for(unsigned x=0; x < mData[ix]; x++) {
for(unsigned y=0; y < mData[iy]; y++) {
for(unsigned z=0; z < mData[iz]; z++) {
cout << x << delimiter << y << delimiter << z << endl;
}
//Close the file when finished
myfile.close();
}
ベクトルにアクセスするには、最初の3つのネストされたループをリサイクルするだけです。
std::ofstream output("blah.csv");
if (!output.is_open())
//error, abandon ship!!!
char delimiter = ','; // char can only hold 1 character, and uses ' not "
// Alternative if you want spaces aswell
// std::string delimiter = ", ";
for (unsigned int iz = 0; iz < mZMax; iz++)
for (unsigned int iy = 0; iy < mYMax; iy++)
for (unsigned int ix = 0; ix < mXMax; ix++)
output << mData[iz][iy][ix].x << delimiter << mData[iz][iy][ix].y << delimiter << mData[iz][iy][ix].z << '\n';
これは、mDataがのオブジェクトを保持my::Vec3f
し、csvの出力を0〜1の正規化された浮動小数点値にすることを前提としています。
コードを改善するもう1つの良い点は、mZMax
ectで固定バッファーサイズを使用する代わりに、読み取りの失敗/成功をチェックすることです。次に、mDataをのような動的コンテナに置き換えstd::vector
ます。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加