c++文本文件中有一组整数,要求排序后输出到另一个文件中。写出代码并详细解释一下为什么?代码简单一些,不要复杂。
读取的文件
写入的文件
代码已加了注释如下:
#include <iostream>
using namespace std;
//冒泡排序函数
void sort(int a[],int n)
{
int i,j;
for(i=0;i<n-1;i++)
for(j=0;j<n-i-1;j++)
if(a[j] > a[j+1])
{
int t = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
}
int main()
{
int a[100];
int len=0,i,n;
FILE *fp;
fp = fopen("1.txt", "r"); //打开读取1.txt
while (fscanf(fp,"%d",&n)>0) //从1.txt读取一个整数给n
{
a[len++] = n; //把n添加到数组中
}
fclose(fp); //关闭1.txt
sort(a,len); //排序
fp = fopen("2.txt", "w"); //创建2.txt文件
for(i=0;i<len;i++)
{
cout << a[i] << " "; //输出数组的值
fprintf(fp,"%d ",a[i]); //数组的值写入到2.txt
}
fclose(fp); //关闭2.txt
return 0;
}
如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!
你是想从txt里面读取数字来排序吧, 用c++反而麻烦
shell只要一句,
sort -o sorted.txt -n test.txt
mark