Search code examples
c++classintpopulate

What is the best way to get a series of integers into a class?


Our assignment is to have a class which takes in integer values one at a time. With those integer values I am supposed to do a multitude of different things. Add them, take the average, find the largest and smallest value etc. I can write the functions for average and largest value and whatever but it is the very beginning that I'm struggling with.

How do I get the user inputs into my class? I have a member function and constructor. The function "next" is what I'll be using to store and pull my numbers from:

class Statistician{
    public:
        Statistician();

        void next (int r);
}

I've tried to write a for loop within the "next" function that will populate and array in order to get each value into the class but this seems to be an extremely tedious way to proceed. I'm not sure what comes next.

Should I use an array and if so how would I write the loop so that the numbers can be put in one at a time? Or is there a different way to do this? Will the class just automatically populate? (That seems unlikely)


Solution

  • The "best" way is rather opinionated. Some people believe the best way is to use a hard coded array (works really good for debugging). Some people prefer to read numbers from a file (consistent, doesn't require a lot of typing). Others use standard input. There are other ways like reading from devices.

    Usually to get numbers into a class, an input method is used. Overloading operator>> is a common technique.

    Here is one example:

    struct Statistician
    {
      std::vector<int> numbers;
      friend std::istream& operator>>(std::istream& input, Statistician& s);
    };
    
    std::istream& operator>>(std::istream& input, Statistician& s)
    {
        int n;
        while (input >> n)
        {
            s.numbers.push_back(n);
        }
        return input;
    }
    

    You could always input the data in another function, then pass the data to your Statistician class.

    Edit 1: A different method
    If you are allergic to overloading operators you can declare an input function:

    struct Statistician
    {
      std::vector<int> numbers;
      void input_data(std::istream& input);
    };
    
    void Statistician::input_data(std::istream& input)
    {
        int n;
        while (input >> n)
        {
            numbers.push_back(n);
        }
    }