CMakeLists.txt
cmake_minimum_required(VERSION 3.10) project(ReadTextFile) # 设置 C++ 标准为 C++11 set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED True) # 添加可执行文件,并链接主程序文件和自定义类的头文件 add_executable(main main.cpp )
main.cpp
#include <iostream> #include <fstream> #include <sstream> #include <vector> #include <string> #include<iomanip> using namespace std; class gnss_data { public: // 原始数据 double time; double lat; double lon; double high; // ENU坐标GNSS的原点 double lat0; double lon0; double high0; // 在ENU坐标下 double x; double y; double z; public: // 初始化 赋予原始数据 gnss_data(double time_,double lat_,double lon_,double high_){ time=time_; lat=lat_; lon=lon_; high=high_; }; bool Set_orinGnss(double lat0_,double lon0_,double high0_){ lat0=lat0_; lon0=lon0_; high0=high0_; } bool Set_ENU(double x_,double y_,double z_){ x=x_; y=y_; z=z_; } }; class GNSS_TextFileReader { public: std::string filename; char delimiter; std::vector<std::vector<std::string>> data; // 二维向量,存储每一行拆分后的数据 std::vector<gnss_data> gnss_List; public: GNSS_TextFileReader(const std::string &filename, char delimiter) : filename(filename), delimiter(delimiter) {} bool readFile() { std::ifstream file(filename); if (!file.is_open()) { std::cerr << "Error opening file " << filename << std::endl; return false; } std::string line; while (std::getline(file, line)) { std::stringstream ss(line); std::string token; std::vector<std::string> row; while (std::getline(ss, token, delimiter)) { // delimiter 分割 row.push_back(token); } data.push_back(row);// 保存string数据double gnss_data gnss_data_i( stod(row[0]),stod(row[1]),stod(row[2]),stod(row[3])); //保存double数据 gnss_List.push_back(gnss_data_i); } file.close(); return true; } void printData() { // for (const auto &row : data) { // for (const auto &col : row) { // std::cout << col << " "; // } // std::cout << std::endl; // } //for (const auto &gnss_List_i : gnss_List) { for(int i=0;i<gnss_List.size();i++){ gnss_data gnss_List_i=gnss_List[i]; cout<< "编号 " << i << " 时间戳 "<< gnss_List_i.time<< " 纬度 " << gnss_List_i.lat << " 经度 " << gnss_List_i.lon<< " 高度 "<< gnss_List_i.high << fixed << setprecision(10)<< endl; } } const std::vector<std::vector<std::string>>& getData() const { return data; } const std::vector<gnss_data>& get_gnss_List() const { return gnss_List; } }; int main() { string path_="/home/dongdong/2project/0data/NWPU/"; path_=path_+"FHY_config/FHY_gps.txt"; GNSS_TextFileReader reader(path_, ' '); // 读取路径 分隔符号 if (reader.readFile()) { //reader.printData(); std::vector<gnss_data> gnss_Lists = reader.get_gnss_List(); for(int i=0;i<gnss_Lists.size();i++){ gnss_data gnss_List_i=gnss_Lists[i]; cout<< "编号 " << i << " 时间戳 "<< gnss_List_i.time<< " 纬度 " << gnss_List_i.lat << " 经度 " << gnss_List_i.lon<< " 高度 "<< gnss_List_i.high << fixed << setprecision(10)<< endl; } } return 0; }