循环遍历文件一次,将行读入添加到数组的对象

时间:2015-02-08 05:07:36

标签: c++

我正在读取一个文件,其中每一行代表一个我将添加到数组的对象。我事先并不知道文件中有多少行,我只能循环一次。另外,我被限制使用普通数组 - 没有其他容器或集合类。这就是我所拥有的:

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;
}

1 个答案:

答案 0 :(得分:1)

每当索引到达当前数组的末尾时,您需要重新分配更宽的数组。像这样。

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;
    }
    /* ... */;
}