03 Lecture Three
03 Lecture Three
Review on Structures
2
3
4
Structure Definition
};
9
Accessing Structure
Members
(Dot Operator)
inv_type x, y; item
x
cost retail
strcpy(x.item, “Red Pen”);
x.cost= 5.99;
on_hand load_time
cout<<x.cost;
cin>>x.retail; item
strcpy(y.item, “Pencil”); y
cost retail
y.cost= 15.5;
cout<<y.cost; on_hand load_time
cin>>y.retail;
10
Example
struct movies_t
{
string title;
int year;
} mine, yours;
int main ()
{
string mystr;
mine.title = "2001 A Space Odyssey"; mine.year = 1968;
...
11
Example (cont.)
...
Enter title: Alien
int main () Enter year: 1979
{
mine.title = "2001 A Space Odyssey"; mine.year = 1968;
My favorite movie is:
cout << "Enter title: ";
cin.getline (yours.title); 2001 A Space Odyssey (1968)
cout << "Enter year: "; And yours is:
cin.getline (yours.year);
Alien (1979)
cout << "My favorite movie is:\n "; printmovie (mine);
cout << "And yours is:\n ";
printmovie (yours);
return 0;
}
item
cost retail
x[0] 25
on_hand load_time
item
cost retail
x[1] -3
on_hand load_time
item
cost retail
x[2] 312
on_hand load_time
item
cost retail
x[3] 89
on_hand load_time
item
cost retail
x[4] -147
on_hand load_time
#define N_MOVIES 3
struct movies_t
{
string title; int year;
} films [N_MOVIES];
int main ()
{
string mystr;
int n;
16
Passing a structure
to a function
// example about passing a structure to a function
#include <iostream> 1000
using namespace std;
struct sample
{
int a,b;
char ch;
};
void main ()
{
struct sample x;
x.a=1000;
fun(x);
}
17
Assigning Structures
void main ()
{
student std1,std2;
std1.id=23;
strcpy(std1.name,”ahmed”);
std1.std_class=‘a’;
std2=std1;
cout<<std2.name<<endl;
cout<<std2.id<endl;
cout<<std2.std_class;
} 18
Pointer to Structures
struct bal
{
float balance;
char name [80];
} person;
20
Nested Structures
struct address
{
char name[50];
char street[50];
char city[50];
char zip[50];
};
struct employee
{
char emp_name[50];
float emp_salary;
address emp_address;
};
21
22