C++对txt文件的操作,要求按行读取文件到数组,然后对内容进行排序输出

2025-03-04 14:29:14
推荐回答(1个)
回答1:

#include
#define MAXLINE 100
void BubbleSort(int r[],int n) //冒泡排序
{
int i,j,temp;
for(i=0;i {
for(j=0;j {
if(r[j]>r[j+1])
{
temp = r[j];
r[j]=r[j+1];
r[j+1]=temp;
}
}
}
}
void main()
{
char c[100];
int i,j,k,temp;
int a[100];
FILE *fp=fopen("QQ.txt","r+");
FILE *fpw;
if(!fp)
{
printf("cannot open the file\n");
return;
}
i=0;
while ((fgets (c, MAXLINE, fp)) != NULL) //逐行读取并转化为int型
{
a[i++] = atoi(c);
}
fclose(fp);
BubbleSort(a,i-1);
fpw=fopen("QQQ.txt","w");
if(!fpw)
{
printf("cannot open the file.\n");
return;
}
for(j=0;j {
printf("%d\n",a[j]);
fprintf(fpw,"%d\n",a[j]);
}
fclose(fpw);
}