I've tried on a few different forums and can't seem to get a straight answer, how can I make this function return the struct? If I try 'return newStudent;' I get the error 'No suitable user-defined conversion from studentType to studentType exists.'
// Input function studentType newStudent() { struct studentType { string studentID; string firstName; string lastName; string subjectName; string courseGrade; int arrayMarks[4]; double avgMarks; } newStudent; cout << "\nPlease enter student information:\n"; cout << "\nFirst Name: "; cin >> newStudent.firstName; cout << "\nLast Name: "; cin >> newStudent.lastName; cout << "\nStudent ID: "; cin >> newStudent.studentID; cout << "\nSubject Name: "; cin >> newStudent.subjectName; for (int i = 0; i < NO_OF_TEST; i++) { cout << "\nTest " << i+1 << " mark: "; cin >> newStudent.arrayMarks[i]; } newStudent.avgMarks = calculate_avg(newStudent.arrayMarks,NO_OF_TEST ); newStudent.courseGrade = calculate_grade (newStudent.avgMarks); }
You can return a structure from a function (or use the = operator) without any problems. It's a well-defined part of the language. The only problem with struct b = a is that you didn't provide a complete type. struct MyObj b = a will work just fine.
Return struct from a function The function returns a structure of type struct student . The returned structure is displayed from the main() function. Notice that, the return type of getInformation() is also struct student .
Structures can be passed as function arguments like all other data types. We can pass individual members of a structure, an entire structure, or, a pointer to structure to a function. Like all other data types, a structure or a structure member or a pointer to a structure can be returned by a function.
Here is an edited version of your code which is based on ISO C++ and which works well with G++:
#include <string.h> #include <iostream> using namespace std; #define NO_OF_TEST 1 struct studentType { string studentID; string firstName; string lastName; string subjectName; string courseGrade; int arrayMarks[4]; double avgMarks; }; studentType input() { studentType newStudent; cout << "\nPlease enter student information:\n"; cout << "\nFirst Name: "; cin >> newStudent.firstName; cout << "\nLast Name: "; cin >> newStudent.lastName; cout << "\nStudent ID: "; cin >> newStudent.studentID; cout << "\nSubject Name: "; cin >> newStudent.subjectName; for (int i = 0; i < NO_OF_TEST; i++) { cout << "\nTest " << i+1 << " mark: "; cin >> newStudent.arrayMarks[i]; } return newStudent; } int main() { studentType s; s = input(); cout <<"\n========"<< endl << "Collected the details of " << s.firstName << endl; return 0; }
You have a scope problem. Define the struct before the function, not inside it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With