Michał Habigier
Michał Habigier

Reputation: 117

Reading file into two arrays

I'm trying to write my own vocabulary with a test for my little brother, but I have a problem when I want to read data from file into two arrays - first with English words, and second with Polish words. File looks alike

black - czarny
red - czerwony etc.

And my function:

void VOC::readout()
{
    fstream file;
    VOC *arr = new VOC;
    string line;
    file.open("slowka.txt");
    if(file.good())
    {
        int i=0;
        while(!file.eof())
        {
            getline(file, line);
            size_t pos = line.find(" - "); 
            int position = static_cast<int>(pos);

            file>>arr[i].en;
            file>>arr[i].pl;
            ++i;
        }
    }
}

I thought it could be a good idea to insert a line into first array until the function finds " - ", and after that insert the rest of line into second array, but I have some problems with that. Could someone help me? I know I can solve it by using std::vector but I care to do that by using arrays.

Upvotes: 0

Views: 876

Answers (1)

Frerich Raabe
Frerich Raabe

Reputation: 94289

If you insist on using plain arrays, you'll first have to count the number of lines in your file and then allocate enough memory. Arrays -- unlike std::vector objects -- won't grow automatically but have a fixed size.

That being said, note that using !file.eof() is not the best way to read a stream until the end is reached. You can use the simpler

std::string line;
while (std::getline(file, line)) {
  // ...
}

idiom instead, which also takes care of error conditions. See this question (and corresponding answers) for more information on that.

Upvotes: 2

Related Questions