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

比如,我要读取的文件名称为QQ.txt
文件内容为:
43343434
63435455
94365654
34365676
76767676
然后读入到一个数组中,(可以完成)
再对其排序,(这个过程无论如何都溢出)
输出到文件QQQ.txt中

34365676
43343434
63435455
76767676
94365654
实在解决不了了,求指点,谢谢了!
#include <stdio.h>
#include <string.h>
#include <iostream.h>
int main()
{
char array[128][128];
FILE *fp;
int i = 0;
if ((fp = fopen("D:\\1\\qq.txt", "r")) == NULL)
{
printf("File Not Exists!!!\n");
return -1;
}
while (fscanf(fp, "%s", array[i]) != EOF)
puts(array[i++]);

fclose(fp);
/*
for(int j=0;j<=128;j++)
{
for(int k=j;k<=128;k++)
{
char temp[128];
if(array[j]>array[k])
{
//temp=array[k];
strcpy(temp,array[k]);
//array[k]=array[j];
strcpy(array[k],array[j]);
//array[j]=temp;
strcpy(array[i],temp);
}
}
}
*/
for(int z=0;z<=128;z++)
{
cout<<array[z]<<endl;
}
return 0;
}
其实我在网上找到了好多,说是可以存到数组中,但是感觉还是连存入数组都无法实现,还是我个人问题?

#include <stdio.h>
#define MAXLINE 100
void BubbleSort(int r[],int n) //冒泡排序
{
int i,j,temp;
for(i=0;i<n;i++)
{
for(j=0;j<n-i;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<i;j++)
{
printf("%d\n",a[j]);
fprintf(fpw,"%d\n",a[j]);
}
fclose(fpw);
}追问

有BUG,我用将近100个QQ号的时候崩溃,修改了相关属性,还是有些问题

追答

怎么崩溃法?这个是按一行一行转化的,应该没问题。那个MAXLINE 是假设你文件内最大有100行,如果数据多可以改大,还有那个a[]数组是储存每行数据的,也应该变大。这两个数据最好大于文件内的号码行数。

追问

我猜测是不是我给的数字超过了int范围了?
QQ.txt
11111534541
11111534546
11111534243
11111534542
11111534548
11111534249
11111534544
11111534545
11111534247
测试无输出

追答

超出int范围了,32位环境下int 范围是-2^32-2^32

温馨提示:答案为网友推荐,仅供参考
相似回答