#include<iostream>
#include<string>
#include<fstream>
using namespace std;
class sequence{
public:
bool add(int ,const string&);
bool del(int);
void output()const;
sequence():last(-1){}
sequence(const char*);
~sequence();
protected:
enum{maxsize=100};
string s[maxsize];
int last;
private:
string filename;
ifstream in;
ofstream out;
};
bool sequence::add(int pos,const string& entry){
if(last==maxsize-1||pos<0||pos>last-1)
return false;
for(int i=last;i>=pos;i--)
s[i+1]=s[i];
s[pos]=entry;
last++;
return true;
}
bool sequence::del(int pos){
if(pos<0||pos>last)
return false;
for(int i=pos;i<last;i++)
s[i]=s[i+1];
last--;
return true;
}
void sequence::output() const{
for(int i=0;i<=last;i++)
cout<<i<<" "<<s[i]<<endl;
}
sequence::sequence(const char* fname){
last=-1;
filename=fname;
in.open(fname);
if(!in)
return ;
while (last<maxsize-1&&getline(in,s[last+1]))
last++;
in.close();
}
sequence::~sequence(){
if(filename=="")
return ;
out.open(filename.c_str());
for(int i=0;i<=last;i++)
out<<s[i]<<endl;
out.close();
}
class sorted:public sequence{
public:
bool adds(const string&);
sorted(){}
sorted(const char*);
protected:
void sort();
private:
using sequence::add;
};
void sorted::sort(){
string temp;
int i,j;
for(i=0;i<=last-1;i++){
temp=s[i+1];
for(i=i;j>=0;j--)
if(temp<s[j])
s[i+1]=s[j];
else
break ;
s[j+1]=temp;
}
}
bool sorted::adds(const string& entry){
int i;
for(i=0;i<=last;i++)
if(entry<=s[i])
break;
return add(i,entry);
}
sorted::sorted(const char* fname):sequence(fname){
sort();
}
int main(){
string inbuffer,where;
int wh;
sequence items("test.dat");
while(true){
cout<<"\nsequence output\n";
items.output();
cout<<"\n1*****add\n"
<<"\n2*****delete\n"
<<"\n3*****quit\n";
getline(cin,inbuffer);
if(inbuffer=="1"){
cout<<"\nitem to add:";
getline(cin,inbuffer);
cout<<"\n add to where?";
getline(cin,where);
wh=atoi(where.c_str());
if(items.add(wh,inbuffer))
cout<<"item added\n";
else
cout<<"item not added";
}
else if(inbuffer=="2"){
cout<<"where to delete:";
getline(cin,where);
wh=atoi(where.c_str());
if(items.del(wh))
cout<<"item deleted\n";
else
cout<<"item not deleted";
}
else if (inbuffer=="3")
break;
}
system("pause");
return 0;
}
有点小问题 请帮忙改正一下 谢了~~~
[此贴子已经被作者于2006-5-31 14:24:54编辑过]