C++读取txt文件指定列数据

//头文件
#include <vector>
#include <iostream>
#include <vector>
#include <iomanip>
#include <fstream>
#include <sstream>
class CReadData
{

	//读取txt数据
	void ReadData();

private:
	vector<pair<double, double>> m_Heightvec;	//存放高度数据
	vector<pair<double, double>> m_Speedvec;	//存放速度数据
	vector<pair<double, double>> m_Pitchvec;	//存放仰俯角数据
	vector<pair <pair<double, double>, double> > m_PositionVec;	//存放飞机位置信息数据
}
//cpp文件
//读取txt数据
void CReadData::ReadData()
{
	//创建流对象
	ifstream ifs;			

	//打开文件
	ifs.open("../../data/file/airplanetest.txt", ios::in);	

	//判断文件是否打开
	if(!ifs.is_open())						
	{
		cout << "打开文件失败!!!";
		return;
	}

	//读取正确匹配特征点
	vector<string> item;				//用于存放文件中的一行数据
	string temp;						//把文件中的一行数据作为字符串放入容器中

	while(getline(ifs, temp))          //利用getline()读取每一行,并放入到 item 中
	{
		item.push_back(temp);
	}

	//记录时间、速度、水平距离、高度和仰俯角
	double time, speed, level, height, pitch;

	for(auto it = item.begin(); it != item.end(); it++)
	{
		//其作用是把字符串分解为单词(在此处就是把一行数据分为单个数据)
		istringstream istr(*it);                
		string str;

		//统计一行数据中单个数据个数
		int count = 0;							 

		//以空格为界,把istringstream中数据取出放入到依次s中
		while(istr >> str)                     
		{
			//获取第1列数据  时间
			if(count == 0)                      
			{
				//数据类型转换,将string类型转换成float,如果字符串不是有数字组成,则字符被转化为 0
				time =  atof(str.c_str());      
			}
			//获取第2列数据	速度
			else if(count == 1)
			{
				//数据类型转换,将string类型转换成float
				speed = atof(str.c_str());

				//将数据压入容器中
				m_Speedvec.push_back(make_pair(time, speed));				
			}
			//获取第二列数据 水平距离
			else if(count == 2)
			{
				//数据类型转换,将string类型转换成float
				level = atof(str.c_str());

			}
			//获取第四列数据 高度
			else if(count == 3)
			{
				//数据类型转换,将string类型转换成float
				height = atof(str.c_str());
				m_Heightvec.push_back(make_pair(time, height));
			}
			//获取第六列数据 仰俯角
			else if(count == 5)
			{
				//数据类型转换,将string类型转换成float
				pitch = atof(str.c_str());    
				m_Pitchvec.push_back(make_pair(time, pitch));

				//存入位置信息
				m_PositionVec.push_back(make_pair(make_pair(level, height), pitch));
			}
			count++;
		}
	}
}

  • 3
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值