decukor
decukor

Reputation: 23

Input elements of structure in C++

I'm trying to implement a structure in C++ 14. I have made a structure that has 3 int values

struct mystruct{
    int a;
    int b;
    int c;
};

In my main function, I'm initializing a structure array in the following way:

int main(){
    mystruct X[] = {{1,2,3}, {4,5,6}};
    .
    .
}

I'll pass this array to a function where I'll perform some operations on it. That function could be like:

int myfunc(mystruct X[]){
    //do something
}

How can I take the values for this array as user input using cin, instead of hardcoding them (perhaps using objects)? I'm not sure how to go about this.

Edit: I was hoping this could somehow be achieved using objects

Upvotes: 2

Views: 1754

Answers (1)

Arnav Borborah
Arnav Borborah

Reputation: 11787

You could implement an input operator for your struct. Something like this would work:

std::istream& operator>>(std::istream& is, mystruct& st)
{
    return is >> st.a >> st.b >> st.c;
}

Now you can read in from a mystruct like this:

mystruct t;
std::cin >> t;

(Note that the function above doesn't handle errors)

Now adding these new structs to an array could be done very simply through the use of a loop. (I would recommend the use of std::vector here).

Here is an example that uses std::vector:

std::vector<mystruct> arr;

for (mystruct t; std::cin >> t;)
{
    arr.push_back(t);
}

myfunc(arr.data()); // Or you could change the signature of the 
                    // function to accept a vector

Upvotes: 7

Related Questions