我刚拿起这段代码打开原始文件,读取数据并将其存储在矢量中。现在,我有一个Java背景,在阅读了一些基础知识之后,我觉得我理解C ++中的工作方式好一点,但我还没有遇到过文件阅读器功能的格式... < / p>
目的是将数据存储在函数中创建的向量中,并将其打印到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();
}
答案 0 :(得分:0)
要访问矢量,您只需回收前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之间的标准化浮点值。
在代码中改进的另一个好处是检查读取失败/成功,而不是使用mZMax
等固定缓冲区大小。然后将mData替换为动态容器,如std::vector
。