此程序将文件从主目录拆分为两个文件,然后使用新名称拼接原始文件。
如何添加计数器以输出新文件中有多少行?
示例:此文件中有80行(放在新文件的末尾)
我该怎么办?
#include<iostream>
#include<fstream>
using namespace std;
void pause();
int main()
{
char filename[] = "Lab2Test.txt";
char filenameA[] = "LabTest-FA.txt";
char filenameB[] = "LabTest-FB.txt";
char filenew[] = "Lab2Test-NEW.txt";
ifstream origin(filename);
ofstream fA(filenameA);
ofstream fB(filenameB);
ofstream fnew(filenew);
if (! origin)
{
cout << filename << " could not be opened." << endl;
return -1;
}
string s;
int i=0;
while(getline(origin, s))
{
if(i % 2 == 1) //odd - write to LabTest-FA
fA << s << endl;
else
fB << s << endl;
i++;
}
fA.close();
fB.close();
ifstream fAA(filenameA);
ifstream fBB(filenameB);
string s1, s2;
while(getline(fBB,s1))
{
fnew << "A. " << s1 << endl;
if(getline(fAA,s2))
fnew << "B. " << s2 << endl;
}
}
void pause()
{
cin.sync();
cout << "Press any key to continue..." << endl;
cin.ignore();
}
答案 0 :(得分:0)
int counter = 0;
counter++;
每当您写信至fnew
时。
答案 1 :(得分:0)
int countA, countB;
if(i % 2 == 1) //odd - write to LabTest-FA
{
fA << s << endl;
countA++;
}
else
{
fB << s << endl;
countB++;
}
i++;
fA << "There are" + countA + "lines in this file" << endl;
fB << "There are" + countB + "lines in this file" << endl;
fA.close();
fB.close();
如果字符串连接不起作用,我很抱歉,用C / C ++已经有一段时间了。