您的位置:首页 > 其它

从文件中读取数据,排序之后输出到另一个文件中

2013-04-01 14:40 357 查看
文件中有一组数据,要求排序后输出到另一个文件中去

两个知识点: 排序、文件操作

代码如下:

#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
void Order(vector<int> &data)//不加 & 符号的话,改变不了 data 向量中的数据。
{
int count=data.size();
int i,j;
int temp;
for (i=0;i<count-1;i++)
{
for (j=0;j<count-1-i;j++)
{
if (data[j]>data[j+1])
{
temp=data[j];
data[j]=data[j+1];
data[j+1]=temp;
}
}
}
}

int main()
{
int i;
vector<int>data;
ifstream in("hua.txt");
int temp;
if (!in)
{
cout<<"打开文件失败"<<endl;
exit(1);
}
while (!in.eof())
{
in>>temp;
data.push_back(temp);
}
in.close();//关闭输入文件流
Order(data);
ofstream out("huahua.txt");
if (!out)
{
cout<<"file open error";
exit(1);
}
for (i=0;i<data.size();i++)
{
out<<data[i]<<"  ";
}
out.close();//关闭输出文件流
cout<<endl;
return 0;
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐