Reputation: 189
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.
Upvotes: 1
Views: 6059
Reputation: 161
if there are same numbers of int in a line for all files, you can get the count of line of the file by calculating the size of it, and then the lines of this file is equal to size(file)/(n*sizeof(int)), n is the number of int for every line. I think you can try instead of read the file twice.
Upvotes: 1
Reputation: 6050
If you don't want use std::vector, you can add a count for in the while loop, if it reaches the up limit of the array, realloc another buffer with size*2 and copy the data to it, then start read the file again.
vector use the same logic.
Upvotes: 1
Reputation: 227370
Here is an idiomatic way of reading numbers from a file into an std::vector<int>
:
#include <iostream>
#include <iterator>
#include <fstream>
#include <vector>
int main()
{
std::ifstream is("inputfile");
std::istream_iterator<int> start(is), end;
std::vector<int> numbers(start, end);
std::cout << "Read " << numbers.size() << " numbers" << std::endl;
}
Upvotes: 2
Reputation: 62472
Use a std::vector
rather that a raw array.
That way you can add to the vector as you read each item, rather than having to read the file once in order to work out how many items are in the file and then again to populate the array.
int main()
{
std::vector<int> data;
int tmp;
ifstream fin("inputfile");
while(fin >> tmp)
{
data.push_back(tmp)
}
return 0;
}
Upvotes: 4