Reputation: 454
I am reading through a file where each line represents an object I will add to an array. I do not know in advance how many lines are in the file, and I can only loop through it once. In addition, I am restricted to using plain arrays - no other container or collection classes. Here's what I've got:
ifstream f;
f.open("lines.csv");
string line;
string theCode;
string theName;
Manufacturer **manufacturers = new Manufacturer*[752]; // this number can't be here - I have to allocate dynamically
int index = 0;
while(getline(f, line))
{
theCode = line.substr(0, 6);
theName = line.substr(7, string::npos);
Manufacturer* theManufacturer = new Manufacturer(atoi(theCode.c_str()), theName);
manufacturers[index++] = theManufacturer;
}
Upvotes: 0
Views: 45
Reputation: 2193
You need to re-allocate a wider array every time when the index reaches the end of a current array. Like this.
int capacity = 752;
while(getline(f, line))
{
if (capacity <= index) {
capacity = (capacity+1) * 2;
Manufacturer **tmp = new Manufacturer*[capacity];
std::copy(manufacturers, manufacturers+index, tmp);
delete[] manufacturers;
manufacturers = tmp;
}
/* ... */;
}
Upvotes: 1