文件中有一组数据,要求排序后输出到另一个文件中去
主要有两个知识点: 排序、文件操作
C++/C代码如下:
[cpp] view plaincopy
- #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 = 0;
- vector<int> data;
- ifstream in("wo1.txt");
- int temp = 0;
- if (!in)
- {
- cout<<"打开文件失败"<<endl;
- exit(1);
- }
- while (!in.eof())
- {
- in>>temp;
- data.push_back(temp);
- }
- in.close();//关闭输入文件流
- Order(data);
- ofstream out("wo2.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;
- }