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

文件中有一组数据,要求排序后输出到另一个文件中去


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

C++/C代码如下:

[cpp]  view plain  copy
  1. #include<iostream>  
  2. #include<fstream>  
  3. #include<vector>  
  4. using namespace std;  
  5. void Order(vector<int> &data)//不加 & 符号的话,改变不了 data 向量中的数据。  采用了引用
  6. {  
  7.     int count=data.size();  
  8.     int i,j;  
  9.     int temp;  
  10.     for (i=0;i<count-1;i++)  
  11.     {  
  12.         for (j=0;j<count-1-i;j++)  
  13.         {  
  14.             if (data[j]>data[j+1])  
  15.             {  
  16.                 temp=data[j];  
  17.                 data[j]=data[j+1];  
  18.                 data[j+1]=temp;  
  19.             }  
  20.         }  
  21.     }  
  22. }  
  23.   
  24. int main()  
  25. {  
  26.     int i = 0;  
  27.     vector<int> data;  
  28.     ifstream in("wo1.txt");  
  29.     int temp = 0;  
  30.     if (!in)  
  31.     {  
  32.         cout<<"打开文件失败"<<endl;  
  33.         exit(1);  
  34.     }  
  35.     while (!in.eof())  
  36.     {  
  37.         in>>temp;  
  38.         data.push_back(temp);  
  39.     }  
  40.     in.close();//关闭输入文件流  
  41.     Order(data);  
  42.     ofstream out("wo2.txt");  
  43.     if (!out)  
  44.     {  
  45.         cout<<"file open error";  
  46.         exit(1);  
  47.     }  
  48.     for (i=0;i<data.size();i++)  
  49.     {  
  50.         out<<data[i]<<"  ";  
  51.     }  
  52.     out.close();//关闭输出文件流  
  53.     cout<<endl;  
  54.     return 0;  
  55. }  

  • 4
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值