c++问题:怎么把一个txt的数据替换另一个txt文件中的一部分数据
1.txt数据如下:01222234556232123595678892.txt012576823168711332265433212359235781145312155...
1.txt数据如下:
0 1 2
22 23
45 56
2 3
21 23 59
5 6
7 8
8 9
2.txt
0 1 2
5 7 6 8 231
6 8 7 11 33
22 6 5 4 33
21 23 59
2 3 5 7 8 11
4 5 31 21 55
8 9 54 22 77
即一行有三个数的数据是相同的ID,把1.txt里的数据替换2.txt中前两列,结果格式跟2.txt格式一样 展开
0 1 2
22 23
45 56
2 3
21 23 59
5 6
7 8
8 9
2.txt
0 1 2
5 7 6 8 231
6 8 7 11 33
22 6 5 4 33
21 23 59
2 3 5 7 8 11
4 5 31 21 55
8 9 54 22 77
即一行有三个数的数据是相同的ID,把1.txt里的数据替换2.txt中前两列,结果格式跟2.txt格式一样 展开
1个回答
展开全部
//希望你能学到一些东西,不只是得到答案。
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
typedef vector<vector<string>> VVS;
typedef vector<string> VS;
void read(const char *file,VVS &vvs)
{
const int BuffSize = 1024;
ifstream fin(file);
char line[BuffSize];
while(fin.getline(line,BuffSize))
{
stringstream ss(line);
VS vLine;
char word[BuffSize];
while(!ss.eof())
{
ss>>word;
vLine.push_back(string(word));
}
vvs.push_back(vLine);
}
}
void write(const char *file,const VVS &vvs1,const VVS &vvs2)
{
ofstream fout(file);
for(int i=0;i!=vvs2.size();++i)
{
for(int j=0;j!=vvs2[i].size();++j)
{
if(j<2 && i<vvs1.size())
{
j==0?fout<<vvs1[i][j]:fout<<" "<<vvs1[i][j];
}
else
fout<<" "<<vvs2[i][j];
}
fout<<endl;
}
}
int main()
{
const char* filein1 = "1.txt";
const char* filein2 = "2.txt";
const char* fileout = "out.txt";
VVS vvs1;
VVS vvs2;
read(filein1,vvs1);
read(filein2,vvs2);
write(fileout,vvs1,vvs2);
return 0;
}
/* out.txt 结果
0 1 2
22 23 6 8 231
45 56 7 11 33
2 3 5 4 33
21 23 59
5 6 5 7 8 11
7 8 31 21 55
8 9 54 22 77
*/
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
typedef vector<vector<string>> VVS;
typedef vector<string> VS;
void read(const char *file,VVS &vvs)
{
const int BuffSize = 1024;
ifstream fin(file);
char line[BuffSize];
while(fin.getline(line,BuffSize))
{
stringstream ss(line);
VS vLine;
char word[BuffSize];
while(!ss.eof())
{
ss>>word;
vLine.push_back(string(word));
}
vvs.push_back(vLine);
}
}
void write(const char *file,const VVS &vvs1,const VVS &vvs2)
{
ofstream fout(file);
for(int i=0;i!=vvs2.size();++i)
{
for(int j=0;j!=vvs2[i].size();++j)
{
if(j<2 && i<vvs1.size())
{
j==0?fout<<vvs1[i][j]:fout<<" "<<vvs1[i][j];
}
else
fout<<" "<<vvs2[i][j];
}
fout<<endl;
}
}
int main()
{
const char* filein1 = "1.txt";
const char* filein2 = "2.txt";
const char* fileout = "out.txt";
VVS vvs1;
VVS vvs2;
read(filein1,vvs1);
read(filein2,vvs2);
write(fileout,vvs1,vvs2);
return 0;
}
/* out.txt 结果
0 1 2
22 23 6 8 231
45 56 7 11 33
2 3 5 4 33
21 23 59
5 6 5 7 8 11
7 8 31 21 55
8 9 54 22 77
*/
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |