0

What I am trying to do is overloading the >> operator of my Book class to take an unknown number of integers from the user in one line. After that, I need to create an array of them.

I tried this:

istream& operator>>( istream& in, Book& b )
{
    int x;

    delete[] b.editionYears;
    b.editionNo = 0;
    b.editionYears = new int[0];

    cin>>x;

    b.addEdition(x);

    return in;
}

And I call this with

cout << A << endl;

in the test class where A is a Book object.

I tried this but in here, when the user enters something like "1 2 3 4", it only deletes the array and adds 1 to it, in the second call it deletes 1 again and adds 2.

What I expect is, if the user enters "1 2 3 4", it should delete editionYears array, create again and add 1,2,3,4 to it.

So how can I do this? Thanks for any help.

Berdan Akyürek
  • 212
  • 1
  • 14

2 Answers2

1

Consider using std::vector instead of dynamically allocated arrays. There are multiple ways to do this. You may ask users to enter the number of integers they are going to enter, you may ask them to enter something like -1 when they are done, or you may ask them to enter all the integers in a single line, then read it into stringstream then convert to ints and push_back to a vector. The first two approaches are trivial to implement, so here's an example implementation for the third way:

#include <iostream>
#include <vector>
#include <sstream>

int main()
{
  std::vector<int> vec;
  std::cout << "please enter numbers in a line" << std::endl;
  std::string line;
  std::getline(std::cin, line);
  std::istringstream ss(line);
  int i;
  while (ss >> i)
  {
    vec.push_back(i);
  }

  return 0;
}
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
1

Your problem is in the use of cin. Try using std::getline.

This other answer may help https://stackoverflow.com/a/5838803/5355195