CSCI 159 Quiz 5 (F24N01/02) Monday lab Sample solutions


Question 1: structs [5 marks]

(i) Provide a definition for a struct type named UserInfo that has two fields, both of type string, named uName and uContact.

Sample solution
struct UserInfo {
   string uName, uContact;
};

(ii) Write a function named fillUser that takes one parameter of type UserInfo, passed by reference, and fills the uName and uContact fields with text obtained through cin.

Sample solution
void fillUser(UserInfo &user)
{
   cout << "Please enter the name (one word): ";
   cin >> user.uName;
   cout << "Please enter the contact data (one word): ";
   cin >> user.uContact;
}

(iii) Write a function named prtUser that takes one parameter of type UserInfo and displays the uName and uContact fields.

Sample solution
void prtUser(UserInfo user)
{
   cout << "User name: " << user.uName;
   cout << ", contact: " << user.uContact;
}


Question 2: arrays of structs [5 marks]
Suppose we have a struct definition as shown below, and getText() and getNumber() functions that each get and return a suitable string/float value from the user.

Write the fillAll function below so that it makes appropriate use of the getText and getNumber functions to fill in both fields of each struct in the array.
struct StoredData {
   string name;
   float  result;
};

// fills the name and result fields of each of the first N elements of the array
void fillAll(StoredData arr[], int N);

Sample solution
void fillAll(StoredData arr[], int N)
{
   for (int s = 0; s < N; s++) {
       arr[s].name = getText();
       arr[s].result = getNumber();
   }
}