recently I have started learning c++, so I'm trying to make a simple grade calculator using my base knowledge (I'm already good with Javascript so i know the basics of programming).
So in this case, I had to return an array of objects from a function call so i can use it later in the program, but I just couldn't find the right way to do so.
So basically i want to return subArr from the getInput function, but I couldn't do that due to my basic knowledge in the language. I tried googling but didn't find any simple solution.
Here is the code and hope it is simple:
//the Subject class:
class Subject {
public:
string name;
float grade;
int factor;
Subject(){};
Subject(string x, float y, int z){
name = x;
grade = y;
factor = z;
}
};
//get Input function declaration
Subject getInput(int num){
//array of objects of type "Subject"
Subject subArr[num];
//a for loop to assign the array's elements
for(int i = 0; i < num; i++){
string name;
float grade;
int factor;
cout << "what is the name of subject " << i+1 <<"? "<<endl;
cin >> name;
cout << "what is the grade of subject " << i+1 << "? "<<endl;
cin >> grade;
cout << "what is the factor of subject " << i+1 << "? "<<endl;
cin >> factor;
subArr[i]=Subject(name, grade, factor);
};
//trying to return the subArr at last
return subArr;
};
//main function
int main(){
//get the number of subjects
int numOfSubjects;
cout << "how many subjects are there? ";
cin >> numOfSubjects;
//trying to receive the subArr from getInput call
Subject subArr = getInput(numOfSubjects);
};
std::vector<Subject>Subject subArr[num];is not valid c++, sincenumis a run-time value. Just use astd::vectorinstead.numto initialize the array's size, also can u give me a code example of using std::vector? i'm a newbie, thanksSubjectdefault constructor.Subject s; std::cout << s.grade;would produce undefined behavior, due tos.gradenot being initialized.