CS 1440 Lab 7

Cover sheetPrevious ActivityNext Activity


Activity 7-1: C++ struct data type

Activity Goals

        To define a struct

        To use structs in various C++ expressions

Activity Procedure

Examine the following C++ program that defines and uses the Student struct described in the prelab.
Especially notice:

1.      How the struct is defined,

2.      Where the struct is defined,

3.      How the struct variables are used

a.       as function parameters

b.      in I/O statements

c.       in arithmetic expressions.

 

#include  <iostream>
#include  <string>

using namespace std;
/* struct definition BEFORE any use of Student */
struct  Student
{
     string  name;
     string  grade;
     double  test1, test2, test3;
     double  average;
};

/* Now we can use the Student data type */
 

void  get_info(Student &s); 
void  print_info(Student s);

int main(void)
{
     int s;
     Student  student1, student2; 

     get_info(student1);
     get_info(student2);
     do {
          cout << "Which student info do you wish to see?"
               << " (1 or 2): ";
          cin >> s;
     } while ( ! (s==1 || s==2));
     if (s == 1) print_info(student1);
     else        print_info(student2);
}

void  get_info(Student & s)  /* Notice reference parameter!! */
{
     char newline;

     cout  <<  "Enter student's name: ";
     getline(cin, s.name);
     cout  <<  "Enter 3 test scores: ";
     cin >> s.test1 >> s.test2 >> s.test3;
     s.average = (s.test1 + s.test2 + s.test3) / 3;
     cout  <<  "Enter final grade (no spaces): ";
     cin  >>  s.grade;
     cin.get(newline); /* left over from cin >> above */
}

void  print_info(Student s)
{
     cout  <<  "Student: "  <<  s.name  <<  endl;
     cout  <<  "\tGrade: "  <<  s.grade  <<  endl;
     cout  <<  "\tTests: "  <<  endl;
     cout  <<  "\t\tAverage: "  <<  s.average  << endl;
     cout  <<  "\t\tScores: "
           <<  s.test1  <<  ","
           <<  s.test2  <<  ","
           <<  s.test3  << endl;
}

Activity Followup

Make a Lab7 directory in your 1440 directory.

Cut and paste the above program into a file named struct.C in your Lab7 directory.

Modify the program so that the struct has an additional data member to hold the student's ID number. The ID number "looks like" a social security number (123-45-6789). Since the ID contains both digits and hyphens, it should be a string. Change the get_info() function so that it asks for and gets the ID number right after it gets tha name. Make suitable changes to print_info() so that the ID number appears in the output in an appropriate place with an appropriate label.