用C++的流操作编写程序从文本文件中读入若干个字符串(每个串长度不超过80个字符),将字符串按字典序(从小到大)排序,结果输出到另一个正文文件中。
题目:
用C++的流操作编写程序从文本文件中读入若干个字符串(每个串长度不超过80个字符),将字符串按字典序(从小到大)排序,结果输出到另一个正文文件中。希望此程序能处理任意多个字符串。
#include<iostream>
#include<string>
#include<fstream>
#include<iomanip>
using namespace std;
struct Str{
string a;
Str *next;
};
int main()
{ Str *first=NULL,*now=NULL;
int i=0;
ifstream is;
is.open("1.txt");
string s;
is>>s;
while(!is.eof())
{ cout<<s<<endl;
{ Str* temp = (struct Str *)malloc(sizeof(struct Str));
temp->a=s;temp->next=NULL;
if(first==NULL)
{
first = temp;
i++;
}
else{
now->next = temp;
i++;
}
now=temp;
}
is>>s;} /*读取文件中的字符串*/
is.close();
now=first;
for(int j=1;j<=i;j++)
{cout<<now->a<<endl;
now=now->next;}
int k=i;
while(k>1)
{now=first;
for(int j=1;j<k;j++)
{Str *now2=now->next;
if(now->a>now2->a)
{s=now->a;
now->a=now2->a;
now2->a=s;}
now=now->next;
}
k--;
}
ofstream os("2.txt");
now=first;
if(os)
{for(int i=1;i<=k;i++)
{os<<now->a;
now=now->next;}}
os.close();
Str *p = first, *q;
while (p!=NULL){
q = p;
p = p->next;
free(q);
}
system("pause");
}
有错误,想请教大神错在哪里orz