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(點(diǎn)號(hào)),X,Y,Z(三維坐標(biāo))排序。
這里提供一種C++讀入"N,X,Y,Z"格式文本文件到Eigen3 Matrix的方法,以及對(duì)應(yīng)的同格式輸出方法
#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));
}
// 讀入相應(yīng)格式的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;
}
// 將矩陣按讀入的相同格式保存至相應(yīng)路徑
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;
}
總結(jié)
到此這篇關(guān)于C++讀入"N,X,Y,Z"格式文本文件到Eigen3 Matrix的文章就介紹到這了,更多相關(guān)c++ 讀入文本文件Eigen3 Matrix內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
構(gòu)造函數(shù)定義為private或者protected的好處
從語(yǔ)法上來講,一個(gè)函數(shù)被聲明為protected或者private,那么這個(gè)函數(shù)就不能從“外部”直接被調(diào)用了。對(duì)于protected的函數(shù),子類的“內(nèi)部”的其他函數(shù)可以調(diào)用之。而對(duì)于private的函數(shù),只能被本類“內(nèi)部”的其他函數(shù)說調(diào)用2013-10-10
C++從文本文件讀取數(shù)據(jù)到vector中的方法
這篇文章主要給大家介紹了利用C++如何從文本文件讀取數(shù)據(jù)到vector中,文章通過實(shí)例給出示例代碼,相信會(huì)對(duì)大家的理解和學(xué)習(xí)很有幫助,有需要的朋友們下面來一起看看吧。2016-10-10
C++的QT項(xiàng)目打包成獨(dú)立可執(zhí)行和發(fā)布的exe文件(項(xiàng)目構(gòu)建過程)
這篇文章主要介紹了C++的QT項(xiàng)目打包成獨(dú)立可執(zhí)行和發(fā)布的exe文件(項(xiàng)目構(gòu)建過程),本文通過實(shí)例圖文相結(jié)合給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-11-11

