【读文件char*转double】

2 篇文章 0 订阅
2 篇文章 0 订阅
本文讲述了在C++中如何处理读取文件时遇到的uint类型变量,重点是将char*类型的指针转换为double*,以便正确解析double数据。作者提到使用QFile和QString进行文件操作,以及对char*指针强转至double*的必要性。
摘要由CSDN通过智能技术生成

读文件char*转double

在读文件时,经常会遇到如

uint8_tuint16_tuint32_t

这种类型的变量,但本质只是表示所占的空间,实际的要转换为int、double类型的变量
以读取double数据为例

QString str = “路径”;
QFile file(str);
char *p;
file.read(p, 8);
double data = *(double*)p; //01

注解01里 p 是 char* 指针,如果用 *p 输出就只会读取一个字节。(至于是高字节还是低字节,学艺不精,不知道,求评论讲解。)

所以需要将 p 的这个 char* 指针强转成double*,double*状态下的 *p 就可以读取完整的 double 变量了

可以如下实现 `Polyhedron` 类: ```c++ #include <fstream> #include <vector> class Point { public: Point(double x, double y, double z) : x_(x), y_(y), z_(z) {} double getX() const { return x_; } double getY() const { return y_; } double getZ() const { return z_; } private: double x_; double y_; double z_; }; class Facet { public: void addVertex(Point* vertex) { vertices_.push_back(vertex); } private: std::vector<Point*> vertices_; }; class Polyhedron { public: Polyhedron(const char* path) { std::ifstream infile(path); std::string line; // 取顶点信息 while (getline(infile, line)) { if (line == "OFF") { continue; } std::istringstream iss(line); double x, y, z; iss >> x >> y >> z; vertices_.push_back(new Point(x, y, z)); } // 取面片信息 int num_facets, num_vertices_per_facet, vertex_index; infile >> num_facets >> num_vertices_per_facet; for (int i = 0; i < num_facets; ++i) { Facet facet; for (int j = 0; j < num_vertices_per_facet; ++j) { infile >> vertex_index; facet.addVertex(vertices_[vertex_index]); } facets_.push_back(facet); } infile.close(); } ~Polyhedron() { for (auto vertex : vertices_) { delete vertex; } } private: std::vector<Point*> vertices_; std::vector<Facet> facets_; }; ``` 在 `Polyhedron` 的构造函数中,首先使用 `ifstream` 取目标OFF文件,然后逐行文件内容。如果取到的行是"OFF",则跳过。否则,使用 `istringstream` 解析该行内容,获取顶点的坐标信息,并使用 `new` 运算符动态创建一个 `Point` 对象,并将其加入到顶点列表中。 接着,取面片信息。首先取面片个数和每个面片包含的顶点数,然后逐个取面片的顶点索引,并根据索引获取对应的 `Point` 指针,并将其加入到面片的顶点列表中。最后将面片加入到面片列表中。 需要注意的是,在 `Polyhedron` 的析构函数中,需要手动释放动态分配的 `Point` 对象,防止内存泄漏。 使用 `Polyhedron` 类取OFF文件的示例代码如下: ```c++ int main() { Polyhedron polyhedron("example.off"); return 0; } ``` 在示例代码中,首先创建一个 `Polyhedron` 类的对象,并传递目标OFF文件的地址作为构造函数的参数。然后程序会自动取OFF文件,并将顶点和面片信息存储在类中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值