Re: Passing Structure to a function

From: kazack (kazack_at_talon.net)
Date: 11/12/03


Date: Wed, 12 Nov 2003 08:56:06 GMT

Okay I follow it now. well in the mean time I have been working on a
project just to understand the concept of structures. It is a little
phonebook program that inputs firstname, last name and phone number. I have
the input, output to file and menu done. I have not yet worked on the
search feature yet. But before I go further I just want to make sure I am
on the right track with all of this. So here is my code I have been working
on.

NOTE: THIS IS NOT A PROBLEM IN ANY OF MY BOOKS: I also do not have no
error checking at all in this program for I am the only one going to be
using it and it is only to understand the segment on Structures:

#include <string>
#include <iostream>
#include <fstream>
using namespace std;

int Menu();
void Menu_Selection(int,struct phonerec phone);
void Input_New_Record(struct phonerec phone);
void Write_To_File(struct phonerec phone);

struct phonerec
 {
  string fname;
  string lname;
  string number;
 };

int main()
{
 phonerec phone;
 int Menu_Choice;
 Menu_Choice = Menu();

   if(Menu_Choice != 3)
   {
   Menu_Selection(Menu_Choice,phone);
   main();
   }
   return 0;
}

void Menu_Selection(int Menu_Choice,struct phonerec phone)
{
 switch(Menu_Choice)
 {
 case 1:
  {
   Input_New_Record(phone);
   break;
  }
 case 2:
  {
   //Reserved For Menu Option 2 to search for record
    // When this feature is set up it will input one record at
// a time into the struct and check to see if search is equal
// and will do this for all records. I know this is not the
//most efficient way but it lets me know if I am using
//structs properly.
   break;
  }
 }
}

void Input_New_Record(struct phonerec phone)
{
 cout << "Enter The First Name: ";
 cin >> phone.fname;
 cout << endl << "Enter The Last Name: ";
 cin >> phone.lname;
 cout << endl << "Enter The Phone Number: ";
 cin >> phone.number;
 Write_To_File(phone);
}

void Write_To_File(struct phonerec phone)
{
 ofstream outdata;
outdata.open("phonebook.dat",ios::app);
 outdata << phone.fname;
 outdata << ",";
 outdata << phone.lname;
 outdata << ",";
 outdata << phone.number;
 outdata << endl;
 outdata.close();
}

int Menu()
{
 int choice;
 while(choice != 1 && choice !=2 && choice !=3)
 {
 cout << endl << endl << endl;
 cout << "1. Input New Record" << endl;
 cout << "2. Search For A Record" << endl;
 cout << "3. Quit Program" << endl;
 cout << "Please Enter A Choice: ";
 cin >> choice;
 }
 return choice;
}

Thank you once again. And also how valuable are unions? From what I have
glanced at all it is is a renamed structure or something along that line.
Is it something worth reading or skip it? I know I really don't want to
skip nothing but I don't want to waste time with stuff that I will not use
either.

Shawn Mulligan