c++按行读取txt

前两天简单的处理了一些数据,记录一下。

目的是取出一个txt文件(wavMaxMinIndex_appear.txt)中6的倍数行的数据,存入一个新的txt(numbers_between_maxMin.txt)文件,然后对此文件按行读入到一个vector中,对齐进行处理。

自己比较渣,编程有点水,什么方便就用什么了,所以分步进行。

前一部分采用python处理,代码如下:

#-*-coding:utf-8-*-

fl=open('wavMaxMinIndex_appear.txt','r')
oddLine=open('numbers_between_maxMin.txt','w')
i=1
for line in fl.readlines():
    if i%6 == 0:
        #print(line)
        oddLine.write(line)
        i += 1
    else:
        i += 1

fl.close()
oddLine.close()

得到如下图所示的数据格式:

21 40 41 40 45 27 12 20 20 
28 20 20 18 38 77 52 27 
43 33 39 99 40 
28 28 35 19 45 27 50 26 11 
106 76 38 

后一部分用c++处理,代码如下:

#include <iostream>
#include <vector>
#include <fstream>

using namespace std;
vector<int> InputDataToVector();

vector<int> InputDataToVector()
{
	vector<int> p;
	ifstream infile("numbers_between_maxMin.txt");
	int number;
	while(! infile.eof())
	{
		infile >> number;
		p.push_back(number);
	}
	return p;
}

int main()
{
	vector<int> res;
	res = InputDataToVector();
	res.pop_back();
	int count[6] = {0};
	for(int i=0; i<res.size(); i++)
	{
		cout << res[i] << " ";
		if(res[i]>=0 && res[i]<20)
			count[0]++;
		else if(res[i]>=20 && res[i]<40)
			count[1]++;
		else if(res[i]>=40 && res[i]<60)
			count[2]++;
		else if(res[i]>=60 && res[i]<80)
			count[3]++;
		else if(res[i]>=80 && res[i]<100)
			count[4]++;
		else
			count[5]++;
	}
	cout << endl;
	cout << "一共有"<< res.size()+104 << "个极值点" << endl;
	cout << "一共有"<< res.size() << "个区间段" << endl;
	cout << "经过统计,在0-20个数据点的区间有" << count[0] << "个" <<endl;
	cout << "经过统计,在20-40个数据点的区间有" << count[1] << "个" <<endl;
	cout << "经过统计,在40-60个数据点的区间有" << count[2] << "个" <<endl;
	cout << "经过统计,在60-80个数据点的区间有" << count[3] << "个" <<endl;
	cout << "经过统计,在80-100个数据点的区间有" << count[4] << "个" <<endl;
	cout << "经过统计,在100个以及100个以上数据点的区间有" << count[5] << "个" <<endl;
	

}

得到结果,如下图:

改进:将文件名直接作为string参数,如下:

vector<float> InputDataToVector(string s)
{
    vector<float> p;
	ifstream infile(s.c_str());
    float number;
    while(! infile.eof())
    {
        infile >> number;
        p.push_back(number);
    }
    return p;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值