将文件的内容传递给数组并打印出来

时间:2012-11-29 19:54:01

标签: arrays file readfile

大家好我坚持练习我必须创建一个txt文件用随机整数填充它,然后将文件读取到一个数组排序然后在另一个文件中打印出来这是我的代码到目前为止:< / p>

 #include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <fstream>
using namespace std;

int main()
{
int *A;
int numbers,lines=0;
srand(time(0));

ofstream myfile;

myfile.open("integers.txt");

if (myfile.fail())
   {
      cout << "Error";
      return 1;
   }

cout<<"\nHow many numbers the file contain : ";
cin>>numbers;
cout<<"\n";


if(myfile.is_open()){

for (int i = 0; i < (numbers-1); ++i) {

myfile << rand()%100 <<"\n";
}
}
A=new int[lines];

ifstream myfile1;
myfile1.open("integers.txt");
 if(myfile1.fail())
    {
      cout << "Error" << endl;
      return 1;
    }

while (!myfile1.eof())
    {
        myfile1 >> A[lines];
        lines++;
    }
    for(int k=0;k<lines;k++)
        cout<<A[k]<<endl;

myfile.close();



return 0;

}

所以问题是如何将文件的内容读取到数组中。每当我在读取文件后打印数组时,输出就是废话。我用谷歌搜索它并找到各种解决方案但这些似乎都没有正常工作。有人告诉我我的错误是什么吗?

1 个答案:

答案 0 :(得分:0)

看起来你在这里创建了一个零长度数组,因为lines被初始化为零。

这一行:

A=new int[lines];

应该是:

A=new int[numbers]