C++获取txt文件的某一列数据,并求其平均值

#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <vector>

using namespace std;

int main() {

	ifstream myfile("iScan-Image-1.txt");
	if (!myfile.is_open()) {
		cout << "Unable to open myfile";
		system("pause");
		exit(1);
	}
	vector<string> vec;
	string temp;
	while (getline(myfile, temp))                    //利用getline()读取每一行,并按照行为单位放入到vector
	{
		vec.push_back(temp);
	}
	vector <double> radius_x;
	for (auto it_x = vec.begin(); it_x != vec.end(); it_x++)
	{
		//cout << *it << endl;
		istringstream is(*it_x);                    //用每一行的数据初始化一个字符串输入流;
		string s_x;
		int pam = 0;
		while (is >> s_x)                          //以空格为界,把istringstream中数据取出放入到依次s中
		{
			if (pam == 9)                       //获取第十列的数据

			{
				double r_x = atof(s_x.c_str());     //做数据类型转换,将string类型转换成float
				radius_x.push_back(r_x);
			}

			pam++;
		}
	}

	double sum_x, ave_x;
	sum_x = ave_x = 0.0;
	cout << "x的数据"<<endl;
	for (auto it = radius_x.begin(); it != radius_x.end(); it++)
	{
		sum_x += *it;
	}
	cout.precision(12);
	ave_x = sum_x / 50;
	cout << ave_x << endl;

	system("pause");
	return 1;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值