CSCI 159 Quiz 5 (F24N01/02) Wednesday lab sample solutions


Question 1: structs [5 marks]

(i) Provide a definition for a struct type named StudentData that has two fields, both of type long, named sID and sGPA.

Sample solution
struct StudentData {
   long sID, sGPA;
};

(ii) Write a function named fillStudent that takes one parameter of type StudentData, passed by reference, and fills the sID and sGPA fields with longs obtained through cin, no error checking is required for this part.

Sample solution
void fillStudent(StudentData &st)
{
   cout << "Please enter the student id as an integer (e.g. 123456): ";
   cin >> st.sID;
   cout << "Please enter the student gpa as an integer (e.g. 3): ";
   cin >> st.sGPA;
}

(iii) Write a function named printStudent that takes one parameter of type StudentData and displays the sID and sGPA fields.

Sample solution
void printStudent(StudentData st)
{
   cout << "ID: " << st.sID << ", gpa: " << st.sGPA;
}
Question 2: arrays of structs [5 marks]
Suppose we have a struct definition as shown below, and getWord and getFloat() functions that each get and return a suitable string/float value from the user.

Write the fillAllInfo function below so that it makes appropriate use of the getWord and getFloat functions to fill in both fields of each struct in the array.
struct Info {
   string word;
   float  data;
};

// fills the word and data fields of each element in the array
void fillAllInfo(Info dataArr[], int size);

Sample solution
void fillAllInfo(Info dataArr[], int size)
{
   for (int i = 0; i < size; i++) {
       dataArr[i].word = getWord();
       dataArr[i].data = getFloat();
   }
}