用C++的流操作编写程序从文本文件中读入若干个字符串(每个串长度不超过80个字符),将字符串按字典序(从小到大)排序,结果输出到另一个正文文件中。

weixin_42321889 2018-05-27 02:37:31
题目:
用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
...全文
1051 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

64,637

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧