Monday, June 13, 2005

Sample Program Using Structures in C++

This is just a simple program illustrating how to use structures, user-defined functions, string functions and switch.

This program is an example to be given to the participants in Pagadian where I will give training on C++ Programming.

#include
#include
#include

struct record
{
char name[200];
int age;
char address[200];
} rec[10];

void add()
{
clrscr();
cout<<"Adding Record\n\n";
for (int num=1;num<=3;num++)
{
cout<<"Enter Name No."< cin>>rec[num-1].name;
cout<<"Enter his/her age: ";
cin>>rec[num-1].age;
cout<<"Enter his/her address: ";
cin>>rec[num-1].address;
}
return;
}
void modify()
{
int y, element;

clrscr();
cout<<"Modify Menu\n\n\n";
cout<<"What record number do you want to modify? ";
cin>>y;
cout<<"\nThe record contains\n\n";
cout<<"Element\t\tData\n";
cout<<"1\t\tName:\t"< cout<<"2\t\tAge:\t"< cout<<"3\t\tAddress:\t"< cout<<"\nWhat element do you like to modify? ";
cin>>element;
switch(element)
{
case 1: cout<<"\n\nNew name:\t";
cin>>rec[y-1].name;
cout<<"\nUpdate successful!";
break;
case 2: cout<<"\n\nNew age:\t";
cin>>rec[y-1].age;
cout<<"\nUpdate successful!";
break;
case 3: cout<<"\n\nNew Address:\t";
cin>>rec[y-1].address;
cout<<"\nUpdate successful!";
break;
default:cout<<"\nNo such element number!";

}
getch();
}
void del()
{
int y;

clrscr();
cout<<"Delete Menu\n\n\n";
cout<<"What record number do you want to delete? ";
cin>>y;
strcpy(rec[y-1].name," ");
rec[y-1].age = 0;
strcpy(rec[y-1].address," ");
}
void display()
{
clrscr();
cout<<"Display Menu\n\n\n";
cout<<"NAME\t\t\tAGE\t\t\tADDRESS\n\n";
for (int x=1;x<=3;x++)
{
if (strcmp(rec[x-1].name," ") != 0 && rec[x-1].age != 0)
cout< }
getch();
}
main()
{
char option;

clrscr();
while (option != 'e')
{
clrscr();
cout<<"MENU\n\n";
cout<<"a. Add\n";
cout<<"b. Modify\n";
cout<<"c. Delete\n";
cout<<"d. Display\n";
cout<<"e. Exit\n";
cout<<"Please enter your choice: ";
cin>>option;
switch (option)
{
case 'a': add();break;
case 'b': modify();break;
case 'c': del();break;
case 'd': display();break;
case 'e': break;
default: cout<<"Invalid selection";
}
}
getch();
return 0;
}

0 Comments:

Post a Comment

<< Home