Friday, 9 August 2013

How to read from file and dynamically allocate an array of int

How to read from file and dynamically allocate an array of int

I need to read some files containing a lot of numbers (int). Lines of
every file are different.
1
3
5
2
1
3
2
I have to read one of those files and create an array of int dynamically.
I'm going to read the file twice because I'm not able to know the length
of the file. Do you know another way ? This is what I did:
int main()
{
int *array;
int tmp, count;
ifstream fin("inputfile");
while(fin >> tmp)
count++;
array = new int[count];
fin.close();
fin.open("inputfile");
int i=0;
while(fin >> tmp)
array[i++]=tmp;
delete[] array;
return 0;
}
Thanks for your help.

No comments:

Post a Comment