C++读入"N,X,Y,Z"格式文本文件到Eigen3 Matrix的方法

发布时间:2021-05-18 09:34:49 作者:小新
来源:亿速云 阅读:248

小编给大家分享一下C++读入"N,X,Y,Z"格式文本文件到Eigen3 Matrix的方法,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

C++读入"N,X,Y,Z"格式文本文件到Eigen3 Matrix,以及相同格式输出方法

很多数据资料的格式类似这样:

1,-2085738.7757,5503702.8697,2892977.6829
2,-2071267.5135,5520926.7235,2883341.8135
3,-2079412.5535,5512450.8800,2879771.2119
4,-2093693.1744,5511218.2651,2869861.8947
5,-2113681.5062,5491864.0382,2896934.4852
6,-2100573.2849,5496675.0138,2894377.6030

其中数据按照N(点号),X,Y,Z(三维坐标)排序。

这里提供一种C++读入"N,X,Y,Z"格式文本文件到Eigen3 Matrix的方法,以及对应的同格式输出方法

#pragma once
#include <fstream>
#include <iostream>
#include <string>
#include <Eigen/Dense>
#include <vector>
#include <cmath>
#include <iomanip>

using namespace std;
using namespace Eigen;

// 字符串分割
void SplitString(const std::string& s, std::vector<std::string>& v, const std::string& c)
{
 std::string::size_type pos1, pos2;
 pos2 = s.find(c);
 pos1 = 0;
 while (std::string::npos != pos2)
 {
 v.push_back(s.substr(pos1, pos2 - pos1));

 pos1 = pos2 + c.size();
 pos2 = s.find(c, pos1);
 }
 if (pos1 != s.length())
 v.push_back(s.substr(pos1));
}
// 读入相应格式的xyz文件
void ReadXYZFile(string filepath, MatrixXd& origin_data)
{
 ifstream infile;
 infile.open(filepath);
 cout << "Reading XYZ File: " << filepath << endl;
 if (!infile.is_open())
 {
 cout << "File Cannot Open" << endl;
 exit(1);
 }

 int r = 0; // 逐行加载数据
 char buffer[100];
 while (!infile.eof())
 {
 // getline只能读成char*,
 // 而SplitString只能切割string,
 // 而atof又只能转化char*到double
 infile.getline(buffer, 100);
 // cout << buffer << endl;
 string line = buffer;
 if (line == "")
 {
 continue;
 }
 vector<string> vector_data;
 SplitString(line, vector_data, ",");
 for (int c = 0; c < origin_data.cols(); c++)
 {
 origin_data(r, c) = atof(vector_data[c].c_str());
 }
 r++;

 }
 return;
}
// 将矩阵按读入的相同格式保存至相应路径
void WriteXYZFile(string filepath, MatrixXd& trans_data)
{
 ofstream outfile;
 outfile.open(filepath, ios::out | ios::trunc);
 for (int r = 0; r < trans_data.rows(); r++)
 {
 for (int c = 0; c < trans_data.cols(); c++)
 {
 if (c < trans_data.cols() - 1)
 {
 outfile << trans_data(r, c) << ',';
 }
 if (c == trans_data.cols() - 1)
 {
 outfile << trans_data(r, c);
 }

 }
 outfile << endl;
 }
 cout << "Write XYZ File: " << filepath << endl;
 outfile.close();
 return;
}

以上是“C++读入"N,X,Y,Z"格式文本文件到Eigen3 Matrix的方法”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. numeric(x+y,y)的长度与位数
  2. python和c++怎么实现旋转矩阵到欧拉角的变换方式

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++

上一篇:C++如何实现结束应用进程小工具

下一篇:C++ 指向类成员的指针是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》