0

I have a program that manages a library. I have 3 classes.

1.- Class Biblioteca (Library) that manages with a dynamic array the books (array is named m_biblio), each position is one book (title...)

2.- Class Llibre (Book) that manages every book, that contains a dynamic array (array is named m_llibre) with the number of copies of every book.

3.- Class Exemplar (copie) with getters and setters for the atributte.

I have a function in the class Library that reads whats is in the file, and sets array size:

    ifstream fitxer;
    string titol, autor;
    int maxllibres = 0;
    int nExemplars=0;
    int i = 0;
    fitxer.open(nomFitxer);

    if (fitxer.is_open())
    {
        fitxer >> maxllibres; //first line of txt reads an integer
        setBiblioteca(maxllibres);
        while (!fitxer.eof())
        {
            fitxer >> titol >> autor >> nExemplars;
            m_biblio[i].setTitol(titol);
            m_biblio[i].setAutor(autor);
            m_biblio[i].setNExemplars(nExemplars);
            i++;
        }
    }
    fitxer.close();

this function calls setBiblioteca(maxllibres); and m_biblio[i].setNExemplars(nExemplars); to set the size of the arrays.

The function of setBiblioteca is like this:

{
m_maxllibres = Maxllibres;
m_biblio = new Llibre[m_maxllibres];
}

It's the same with setNExemplars.

With this situation, the program fails to set the size of the array. VS output is this std::bad_array_new_length. And I don't know what's the problem. If you could help I'll be very happy to solve this problem.

Thaaanks!

pixel
  • 9
  • 1
  • 5
    If you can use a `std::vector` instead of pointers and `new`. – NathanOliver Jun 14 '18 at 16:48
  • Unrelated: [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – user4581301 Jun 14 '18 at 17:09
  • And also, you should checking if this input statement `fitxer >> titol >> autor >> nExemplars;` actually works. –  Jun 14 '18 at 17:14
  • Semi-related: `fitxer >> maxllibres;` does not test to make certain the read succeeded. You want to wrap that in an `if` statement (`if (fitxer >> maxllibres) { rest of code }`) and after that you also want to test that `maxllibres` is a reasonable value (Positive, does not exceed available memory...), so `if (fitxer >> maxllibres && maxllibres > 0 && maxllibres < TOO_BIG_NUMBER) { rest of code }` – user4581301 Jun 14 '18 at 17:14
  • VS has told you that your array's length is bad. Your next step is to find out what that length is (via debugging statements or a debugger). You know what you intended the length to be, but what are the actual values of `maxllibres` and `nExemplars`? – JaMiT Jun 14 '18 at 19:18
  • Ok, thank you guys. I'll try to debug again. May be, the input statement from txt doesn't work as it should work. – pixel Jun 18 '18 at 15:26
  • Thank all of you for your help!!! – pixel Jun 18 '18 at 15:26

0 Answers0