例如有一个文本文件a.txt中有文本如下:
010001011030101011012016101011013022302040607140
020002022060202022022016101011013021401030502140
030003033090103033012017101011013025202030502070
040004041030204043022017101011013033102040603080
050005052060105051012018101011013011201030506130(一共一百行)
想要提取每行第35和36位存入b.txt,b.txt中文本格式如下:
22
21
25
33
11
然后根据另一文本文件c.txt中数据,c.txt中数据如下:
11 0.8
21 0.1
22 0.2
25 0.6
33 0.5
得到b.txt中每行数据在c.txt中所对应的小数,全部加和后赋值给a显示出来。
小白求代码!!!
思路:用数组读取txt内容,对数组进行操作。我把三个文件内容都输出到屏幕了。
#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <string>
const int N = 5; //a.txt行数
const int M = 5; //c.txt行数
using namespace std;
int main()
{
ifstream fin("a.txt");
ofstream fo("b.txt");
char s[N][100], b[N][10],c[M][10];
int n = 0,i,j=0;
float sum = 0;
while (N - n) //读取a.txt,写入b.txt
{
fin.getline(s[n], 100);
cout << s[n] << endl;
fo << s[n][34]<<s[n][35]<<endl;
n++;
}
fin.close();
fo.close();
ifstream fi1("b.txt");
ifstream fi2("c.txt");
for (i = 0; i < N; i++) //读取b.txt
{
fi1.getline(b[i], 10);
cout<< b[i]<<endl;
}
for (int i = 0; i < M; i++) //读取c.txt
{
fi2.getline(c[i], 10);
cout << c[i] << endl;
}
for(int i=0;i<N;i++) //判断求和
for(int j=0;j<M;j++)
if (c[j][0] == b[i][0] && c[j][1] == b[i][1])
{
sum += (float)(c[j][5]-'0')/ 10;
break;
}
cout << sum << endl;
fi1.close();
fi2.close();
system("pause");
return 0;
}
追问大神,我能再问一下,最后要是不求和的话,怎么把b中对应c的小数放在一个数组输出来呢😋
C++ 中有个非常好用道的东西ifstream 通过它将文件读取进来
使用循环方法,用getline函数获取每内一行容的内容
将读取的每一行的内容找到第35和36位提取
通过ofstram写入新文件。