C++逐行解析Txt文本文件,并将相应的字符串转换为double等类型

直接上代码

// ReadTxt.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include<iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;


struct CoordinateData
{
	//double x, y, z, a, b, c, d;
	double v[7] = { 0.0 };
};
// 读取坐标信息文本文件,并解析到容器中
bool readCoordinateDataText(const std::string& src_file, std::vector<CoordinateData>& data);

int main()
{
    std::cout << "Hello World!\n";

	std::vector<CoordinateData> coordinate_data;
	bool succeed = readCoordinateDataText("000513U01N_Quaternion(3)(1).txt", coordinate_data);
	if (!succeed)
	{
		// 未读出文件
	}
	return 0;
}

bool readCoordinateDataText(const std::string& src_file, std::vector<CoordinateData>& data)
{

	data.clear();
	// define the file to be read
	std::ifstream fin(src_file, std::ios::in);

	if (!fin.is_open())
	{
		return false;
	}
	// set the buffer size
	char line[1024] = { 0 };
	// read each line
	while (fin.getline(line, sizeof(line))) {
		// set the current line to a stringstream
		std::stringstream ss(line);

		while (!ss.eof()) {
			//double p[7];
			CoordinateData p;
			std::string token;
			for (unsigned dim = 0; dim < 7; dim++) {
				ss >> token;
				p.v[dim] = atof(token.c_str());
			}
			std::cout << "<" << p.v[0] << " " << p.v[1] << " " << p.v[2]
				<< p.v[3] << " " << p.v[4] << " " << p.v[5] << " " << p.v[6] << ">" << std::endl;

			data.push_back(p);

		}
	}

	fin.close();
	return true;
}

 

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值