0

So I'm writing a program for a database storage, the first step is to load the information from a text file to a struct array. However, I get an error message during the reading/writing process saying that the program is going into an out of range instance.

while (!inFile.eof())
{
    getline(inFile, dataLine);              //saves the line of the file into a string

    a[i].name = dataLine.substr(0, 17); // 18
    a[i].author = dataLine.substr(19, 33); // 15
    a[i].vol = dataLine.substr(35, 60); // 26
    a[i].pub = dataLine.substr(62, 77); // 16
    a[i].year = dataLine.substr(79, 82); // 4
    a[i].price = dataLine.substr(84, 91); // 8
    a[i].copies = dataLine.substr(93, 96); // 3


    i++;    //moves through the array after each line.
    count++;    //counts how many lines/items there are in the file entered for the program
}

I've narrowed the problem down to this section, but I can't seem to figure out what's causing it to go wrong.

terminate called after throwing an instance of 'std::out_of_range'
what():  basic_string::substr: __pos (which is 19) > this->size() (which is 0)
Aborted

And here is the error message I've gotten.

  • First and foremost, [**this is wrong**: `while (!inFile.eof())`](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). Fix that. Second, update your question to include a [minimal, **complete** verifiable example](https://stackoverflow.com/help/mcve) that reproduces your problem, including any input required to reproduce the issue. – WhozCraig Jan 27 '17 at 23:02
  • @WhozCraig That's probably the reason for the error. Because of that, the loop isn't stopping at the end of the file. It does an extra `getline()`, which returns a zero-length string, and then `dataLine.substr(19, 33)` gets an error. – Barmar Jan 27 '17 at 23:04

1 Answers1

0

The specific error you are facing is that the length of dataLine is zero and you are trying to substring. Exception is described here: http://www.cplusplus.com/reference/string/string/substr/

Doing an additional check for the length of the string would resolve this issue.

if (dataLine.size() >= 97) {
    ...
}
Darryl Johnson
  • 423
  • 3
  • 10
  • More specifically, each of those substr calls should ensure the `dataLine.length()` is at least as wide as the right end of the substring request, otherwise it's pointless. At a minimum, it should check that `dataLine.length() >= 97`, not just greater than zero. – WhozCraig Jan 27 '17 at 23:07