给你封装了个类,自己看吧
#include<iostream>
#include<fstream>
using namespace std;
class Stats
{
private:
char currChar;
int times;
ifstream in;
ofstream out;
public:
Stats()
{
currChar=0;
times=0;
}
~Stats();
bool openIn(const char* filename);
bool openOut(const char *filename);
bool read();
void write();
};
Stats::~Stats()
{
in.close();
out.close();
}
bool Stats::openIn(const char* filename)
{
in.open(filename);
if(!in) return false;
return true;
}
bool Stats::openOut(const char* filename)
{
out.open(filename);
if(!out) return false;
return true;
}
bool Stats::read()
{
if(!in) return false;
in>>currChar;
if(currChar==EOF) return false;
times=1;
while(in.peek()==currChar)
{
in>>currChar;
times++;
}
return true;
}
void Stats::write()
{
if(!out) return;
if(times>4) out<<currChar<<"*"<<times;
else for(int i=0;i<times;i++) out<<currChar;
currChar=0;
times=0;
}
int main()
{
Stats s;
if(!(s.openIn("text.txt")&&s.openOut("result.txt")))
{
cout<<"Error opening file";
return 1;
}
while(s.read()) s.write();
return 0;
}