[英]Accessing vectors and exporting data to a file
我刚刚拿起了这段代码,该代码打开一个原始文件,读取数据并将其存储在向量中。 现在,我拥有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之间的标准化浮点值。
改进代码的另一件好事是检查读取失败/成功,而不是对mZMax
ect使用固定的缓冲区大小。 然后将mData替换为动态容器,例如std::vector
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.