0

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.

4
  • 1
    arr points to one single VOC object and is not an array. Since you don't know how many, a std::vector is your best option.
    – crashmstr
    Feb 12, 2016 at 15:30
  • 1
    What are you doing with int position = static_cast<int>(pos);? Feb 12, 2016 at 15:37
  • I thought comparing size_t with int can cause an overflow, am I wrong? Feb 12, 2016 at 15:42
  • Rather than using 2 arrays, you may want to use one std::vector of structures that contain both words. Feb 12, 2016 at 15:54

1 Answer 1

2

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.

1
  • Thanks! I just want to learn using arrays perfectly, and then move into std::vector. Can't believe I could forget about so obvious thing like allocating memory. And is string::find a good idea to use it here? Feb 12, 2016 at 15:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.