Hi guys! So far I have had a great experience in this forum with all the help one is able to receive it makes learning C++ very enjoyable.
My question was with structures and functions.
Currently my goal is to call a value returning function, ask for the structure's attributes, store it and then display it, but every time time I call it it generates a random number and it doesn't seem to store it under student s1.
I am not trying to use pointers, overload operators or anything like that just simple coding methods.
Try passing the struct to the function by reference instead of by value. If you pass by value, you're passing a copy of the original and updating the age of the copy, not the original.
What i essentially want to do is be able to take values from the getInfo function and store said values into two different structures that i declared in main, s1, s2 and eventually s3. But I want to only use getInfo value returning, so I'm not sure if by reference would be the best option since i want to make it generic for several structures?
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::ios;
#include <string>
using std::getline;
using std::string;
#include <cstdlib> // for atoi and atof
struct Student //attributes
{
int age;
double gpa;
};
Student getInfo(Student);
int main()
{
Student s1,s2,s3;
getInfo(s1);
getInfo(s2);
}
Student getInfo(Student anyStudent) // want to collect data from here for 2 different students s1, s2
{
cout << "enter age "<< endl;
cin >> anyStudent.age;
cout << "enter gpa "<<endl;
cin >> anyStudent.gpa;
return anyStudent;
}
Again you defined your function to return a Student why are you not using the value returned.
By the way why are you passing a value into the function? Why not just use a Student that is local to that function?
1 2 3 4 5 6 7 8 9 10
Student getInfo() // You're returning a student be sure to use that returned value.
{
Student anyStudent;
cout << "enter age "<< endl;
cin >> anyStudent.age;
cout << "enter gpa "<<endl;
cin >> anyStudent.gpa;
return anyStudent;
}
And don't forget if you want to use the value returned from the function you need to store that information somewhere. Perhaps you should consider assigning the value returned to some variable in main()?
You're mixing two idioms here and neither one is correct.
1) If you want to pass Student as an argument, then you need to pass it by reference, otherwise getInfo() is operating on a copy and any changes are lost when getInfo() exits.
If you pass Student by reference, there is no need to return it by value.
void getInfo (Student & anyStudent)
2) You're returning Student at line 39, but you ignore the return value at lines 26,27. If you're going to use the return value, you might as well eliminate the argument to getInfo() as it is not needed.