上面我们学习了那么多的字符串的有关函数,那我们下来就好好利用一下,编写一个简单的文本编辑器l
具体的实现代码如下所示:
点击(此处)折叠或打开
#include
#include
#include
using namespace std;
class TextEditer
{
public:
TextEditer(string input,string output);
void showmenu();
void insert(string str1,string str2);
void erase(string str);
void next();
void quit();
void run();
void replace(string str1,string str2);
private:
ifstream myInstream;
ofstream myOutstream;
string myLine;
};
点击(此处)折叠或打开
#include
#include
#include
#include
using namespace std;
#include"text.h"
void eatBlanks()
{
char blank;
while(cin.peek()==' ')
cin.get(blank);
}
TextEditer::TextEditer(string inputFile,string outputFile)
{
myInstream.open(inputFile.data());
myOutstream.open(outputFile.data());
if(!myInstream.is_open()||!myOutstream.is_open())
{
cerr<<"Error in opening files";
exit(-1);
}
}
void TextEditer::run()
{
showmenu();
cout<<"Enter an editing command following each prompt>\n\n";
getline(myInstream,myLine);
cout<<"Text: "<
char command;
string str1,str2;
for(;;)
{
if(myInstream.eof()) break;
cout<<'>';
cin>>command;
cin.ignore(1,'\n');
switch(toupper(command))
{
case 'I':eatBlanks();
getline(cin,str1);
cout<<"Insert before what string?";
getline(cin,str2);
insert(str1,str2);
break;
case 'D':
eatBlanks();
getline(cin,str1);
erase(str1);
break;
case 'R':eatBlanks();
getline(cin,str1);
cout<<"with what ?";
getline(cin,str2);
replace(str1,str2);
break;
case 'N':next();
break;
case 'Q':
quit();
break;
default:
cout<<"\n***Illegal command***\n";
showmenu();
cout<<"Text: "<
}
if(!myInstream.eof())
cout<<"Text: "<
}
cout<<"\n***Editing compelete***\n";
}
void TextEditer::showmenu()
{
cout<<"editing commands are:\n"
<<"I str: insert string str before another string\n"
<<"D str:delete string str\n"
<<"R str: replace string str with another string\n"
<<"N: Get next line of text\n"
<<"Q:quit editing\n";
}
void TextEditer::insert(string str1,string str2)
{
int position=myLine.find(str2);
if(position!=string::npos)
myLine.insert(position,str1);
else
cout<
}
void TextEditer::erase(string str)
{
int position=myLine.find(str);
if(position!=string::npos)
myLine.erase(position,str.length());
else
cout<
}
void TextEditer::replace(string str1,string str2)
{
int position=myLine.find(str1);
if(position!=string::npos)
myLine.replace(position,str1.length(),str2);
else
cout<
}
void TextEditer::next()
{
myOutstream<
getline(myInstream,myLine);
cout<<"\nNext line:\n";
}
void TextEditer::quit()
{
myOutstream<
for(;;)
{
getline(myInstream,myLine);
if(myInstream.eof()) break;
myOutstream<
}
}
点击(此处)折叠或打开
#include
#include
using namespace std;
#include"text.cpp"
int main()
{
string inFilename,outFilename;
cout<<"Enter the name of the input file:";
getline(cin,inFilename);
outFilename=inFilename+".out";
cout<<"the outfile is:"<
TextEditer editer(inFilename,outFilename);
editer.run();
}
阅读(3632) | 评论(0) | 转发(1) |