溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

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

發(fā)布時間:2021-05-18 09:34:49 來源:億速云 閱讀:257 作者:小新 欄目:編程語言

小編給大家分享一下C++讀入"N,X,Y,Z"格式文本文件到Eigen3 Matrix的方法,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

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

很多數(shù)據(jù)資料的格式類似這樣:

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

其中數(shù)據(jù)按照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; // 逐行加載數(shù)據(jù)
 char buffer[100];
 while (!infile.eof())
 {
 // getline只能讀成char*,
 // 而SplitString只能切割string,
 // 而atof又只能轉(zhuǎn)化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的方法”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

c++
AI