Returning struct array from a function

The function only returns the last element, how can I return all the elements of the array?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
  #include <iostream>

using namespace std;

const int N=2;
struct Deg
{

	int time;
	double deg;

	
};
Deg getInfo();
int main(){
	
	Deg t;
	t=getInfo();
	for (int i=0; i<N; i++){
		cout 
			<<endl
			<<"Time "<<t.time<<endl
			<<"Degree: "<<t.deg<<endl;
	}
	cout<<endl;
}

Deg getInfo(){
	Deg a;
		for (int i=0; i<N; i++){
		cout
			<<"\nEnter time: ";
		cin>>a.time;
		cout<<"Enter the degree: ";
		cin>>a.deg; 
	}
	return a;
}
how can I return all the elements of the array?

I don't see any arrays in your code.
1
2
3
4
5
6
7
8
9
10
11
Deg getInfo(){
	Deg a;
		for (int i=0; i<N; i++){
		cout
			<<"\nEnter time: ";
		cin>>a.time;
		cout<<"Enter the degree: ";
		cin>>a.deg; 
	}
	return a;
}


I want to return all
time
and
deg
to the main, I tried to do this, but it has errors.
1
2
3
4
5
6
7
8
9
10
11
[code]Deg getInfo(){
	Deg a;
		for (int i=0; i<N; i++){
		cout
			<<"\nEnter time: ";
		cin>>a.time[i];
		cout<<"Enter the degree: ";
		cin>>a.deg[i]; 
	}
	return a;
}

[/code]
If you wanted to return an array, you would need to dynamically allocate it, which is not preferred. Preferably you'd use a vector, which avoids the issues associated with dynamic memory.
1
2
3
4
5
6
7
8
9
void getInfo( Deg a[] ){
        for (int i=0; i<N; i++){
        cout
            <<"\nEnter time: ";
        cin>>a[i].time;
        cout<<"Enter the degree: ";
        cin>>a[i].deg; 
    }
}
Last edited on
Thanks for advice!
If you return a proper container (vector<Deg>), your main becomes much nicer too:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
vector<Deg> getInfo() {
  vector<Deg> v;
  for (int i=0; i<N; i++) {
    Deg a;
    cout <<"\nEnter time: ";
    cin >> a.time;
    cout << "Enter the degree: ";
    cin >> a.deg;
    v.push_back(a);
  }
  return v;
}

int main() {
  for(const auto& t: getInfo()) {
    cout << '\n'
         << "Time " << t.time << '\n'
         << "Degree: " << t.deg << '\n';
  }
  cout << '\n';
}
Thanks so much!
Topic archived. No new replies allowed.