C++ Tutorial: Building an Address Book Program

Author: Ronald S. Holland
at
Total Application Works

ronholland@sumtotalz.com





To visit my site

HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript ]


To contact us

2002 - 2016 All Rights Reserved Total Application Works


  • Tell a friend about this site (copy and paste the following HTML page into a file (e.g., using Notepad).)
  • <html>
    <head>
    <title>Example of a link </title>
    </head>
    <body>
    <a href="http://sumtotalz.com/TotalAppsWorks/AddressBook_II/AddressBook_Prog_Tut.html">
    AddressBook Program Tutorial </a>
    </table>
    </body>
    </html>
  • Download source
  • [Screenshot


Introduction

This tutorial is intended for people who have some experience with C++. In this example, we will build an Address Book application that uses persistent data. In order for you to follow this tutorial, you will need a C++ compiler. I don't believe in buying something if you can get it for free. At this point, if you don't have a compiler, you can download one for free from


There are some books on the market that come with a CD containing a compiler e.g., Sam's Teach Yourself C++ in 21 Days. This is not an endorsement of the book, but simply a suggestion on how to get a top quality C++ compiler. If you buy a book, make sure it contains a copy of a C++ Compiler or preferably a copy of the MS Visual Studio C++. First year college textbooks on C++ may also be a good source. Before you spend any money, download a free copy of the Microsoft's Visual Studio C++ 2008 or 2010 Edition.

Requirements

Following are the requirements for the application we are tasked to build.

  1. Build an Address Book C++ console application.
  2. The application should be based on:
    • A class definition in a header file.
    • The class implementation in a .cpp file
    • The application driver in a separate .cpp file.
  3. The data in the class definition should include:
    • recordID;
    • firstName
    • lastName
    • address
    • city
    • state
    • zip
    • telephone
    • fax
    • email
  4. The behavior (methods) should include:
    • AddRec - Add a new record to the file
    • UpdateRec - Get data to update a record
    • DeleteRec - Delete a record from the file
    • DisplayData - Display all records in the file
  5. When performing one of the above behaviors listed in requirement 4, prompt the user for the required data. When adding an address record, the prompts might look like:
     
    Enter first name
    
    Enter last name
    
    Enter address
    
       ...
     
  6. Create a file to maintain the persistent data. To maintain this file, create the following behaviors:
    • Read - Read a record from the file
    • Write - Write a record to the file
  7. If the file that maintains the persistent data is empty, create data to initialize the file.
  8. Use Holland's OOP Programming Design Model to build this program.
In the next section we will describe Holland's OOP Programming Design Model.

What is the Holland's OOP Programming Design Model?

In object-oriented programming, programming revolves around the data. So in this style, the top is the data. It might be depicted as follows:

Holland's OOP Programming Design Model
  
          +--------------+
          |      Data    |<----+  
          +-------+------+     | 
                  ^            |
                  |----------->+
                  V            ^
          +-------+------+     |
          |   Top-down   |     | 
          |  Structured  |<----+
          |  programming |     |
          |  on Classes  |     | (step-wise)
          |  and methods |     | (refinement)
          +--------------+     | (as needed or as the) 
                  |            | (application ages)
                  +------------+ 
 
  
Figure 1:


The address data is entered via prompts from the application. This data is initially defined by requirement 3 above. As the application ages, the address data/record may change. Requirement 4 lists the initial methods to be built with this application. In the next section, I will describe how to build the Address book template.

What is a Template?

If you look in a dictionary, template is defined as

    a pattern, usually in the form of a thin plate of metal, wood, plastic, etc., for forming an accurate copy of an object or shape

Our template looks like:

  
/***************************************************
 * Comments
 * 
 **************************************************/

// #include header files

/* All C++ applications must have one main() function */
void main() {
   //code to do something        
}
  
Figure 2: Template


In the above template, { begins the body of the program (where the code resides), and } indicates the end of the main() function. You should try to compile and execute the above template. We will use this template for our application driver. As we proceed with stepwise refinement, we will "flesh-out" our address book class template.

A class definition consists of member variables and member functions, which are all defined within enclosing braces ({ and }). This class definition will serve as a template for any class we define. For instance, a typical class definition might look like:

  
class className {
   public:             // access specifiers
      className() ;    // constructor
      void funct_1();
      void funct_2();
      void funct_3();
   private:
      int    var1;
      float  var2;
      char   var3;
};
  

Figure 3: Template II


The implementation .cpp file contains the implementation of the functions declared in the class definition file. Figure 3 shows the next rung in our step-wise refinement.

Writing Our Address Book Class Definition

To create our Address Book class definition, we will use requirements 3 and 4 defined above.

  

class className {
   public:               // access specifier 
      className() ;      // constructor
      void AddRec() ;    // Add a new record to the file
      void UpdateRec ;   // Get data to update a record 
      void DeleteRec ;   // Delete a record from the file
      void DisplayData ; // Display all records in the file

   private:              // access specifier 
      int recordID;
      char firstName[ 15 ] ; 
      char lastName[ 15 ] ;  
      char address[ 15 ] ;  
      char city[ 15 ] ;  
      char state [ 15 ] ; 
      char zip[ 15 ] ;  
      char telephone[ 15 ] ;  
      char fax[ 15 ] ;  
      char email[ 15 ] ;  
};
  
Figure 4: Address Book Class Definition


We will add some additional functions to this definition; however, the above definition will be our blueprint for the implementation file, as we proceed with our step-wise refinement.

Writing DOS Style Menus

A DOS style menu is simply displaying an options panel from which the user can select options. It might look like:

Figure 5: DOS Style Menus


The above depiction in Figure 5 will be used in our next refinement step. The code to implement this menu looks like:

  

                        

    while( loopCtl) {

      n = ab.RecordCount();  // how many records in file?

      cout << "+-----------------------------------------+"  << endl;
      cout << "|                                         |"  << endl;
      cout << "|   ADDRESSBOOK OPTION PANEL              |"  << endl ;
      cout << "|                                         |"  << endl;
      cout << "| 1- Add an address record                |"  << endl;
      cout << "| 2- Update an address record             |"  << endl;
      cout << "| 3- Delete an address record             |"  << endl;
      cout << "| 4- Display all of the address records   |"  << endl;
      cout << "| 5- Quit                                 |"  << endl;
      cout << "|                                         |"  << endl;
      cout << "+-----------------------------------------+"  << endl;

          cout << " " << endl;
          cout << "Please enter a number for one of the above options." << endl;

      cin >> str ;


	  option_1 = atoi(str);


          switch (option_1) {
             case 1:
                ab.AddRec( n ) ;
             break;

             case 2:
		ab.UpdateRec( n ) ;
             break;

             case 3:
		ab.DeleteRec( n ) ;

             break;

             case 4:
                         // Dislpay the list
                system( "Cls" );
                cout << "\n\n\n\n" << endl;
                   ab.DisplayData( n )   ;           

                cout << "\n\n\n\n" << endl;
                system( "Pause" );
             break;

             case 5:
                loopCtl = false;
             break;

             default:
                cout << "Please enter a number from one through five" << endl ;

		  }

          system( "Cls" );

   }

  
Figure 6: Code for DOS Style Menus


The above depiction in Figure 6 will be used in our next refinement step.

File Streams

You must include header files <iostream> and <fstream> if you want to perform C++ file processing. In the following code snippet, <ifstream> opens a file for reading

  
ifstream infile;                           // make stream
infile.open("Addressbook.dat", ios::binary);
  

and <ofstream> opens a file for writing.
  
ofstream onfile;                           // make stream
onfile.open("Addressbook.dat", ios::app | ios::binary);
  

Figure 7: File I/O Streams


The above depiction in Figure 7 will be used in our next refinement step. The following chart shows a few modes that might be used in accessing a file.

Mode Description
ios::ate Open a file for output and move the file pointer to the end of the file. Data can be written anywhere in the file.
ios::app Open a file for output and write all data at the end of the file.
ios::out Open a file for output.
ios::in Open a file for input.
ios::binary Open a file for binary (i.e., non-text) input or output.
ios::trunc Erase the file's contents if it exists.
ios::end Set the file pointer at the end of the file.
ios::beg Set the file pointer at the beginning of the file.
Figure 8: File open modes


If you want to calculate the number of records in the file, you might create an algorithm like the following:
  
   ifstream infile;
   infile.open("Addressbook.dat", ios::binary);
   infile.seekg(0, ios::end);    // go to 0 bytes from end
                                 // calculate number of address records
   return (int)infile.tellg() / sizeof( AddressBook );

  
Figure 9: Calculate the number of records in the file


The above depictions in Figure 8 and 9 will be used in our next refinement step.

Final Class Definition

The final class definition looks like:

  
class AddressBook    {                 
    
   protected:
      
      int  recordID;
      char firstName[30];
      char lastName[30];
      char address[30];
      char city[30];
      char state[15];
      char zip[15];
      char telephone[20];
      char fax[30];
      char email[30]; 

   public:
      AddressBook() ;
      ~AddressBook() ;
      void DisplayData( int n )  ; // Display all records in the file
      void AddRec( int n )  ;      // Add a new record to the file
      void DeleteRec( int n )  ;   // Delete a record from the file
      void UpdateRec( int ) ;      // Get data to update a record 
      void UpdateData( long n) ;   // Update data in the file
      void InitData() ;            // init file with records
      void ReadData(int);          // read record from file
      void WriteData();            // write record to file
      static int RecordCount();    // return number of records in file
                                   
};
  
Figure 10: Final Class Definition


The above class definition in Figure 10 will be used to implement the addressbook.cpp code. As we code our address book program, our step-wise refinement will continue.

Conclusions

I updated to and used Microsoft's Visual Studio C++ 2008 Edition to compile and execute this example. With this tutorial and source, you should have the necessary information to build this Address Book example. Enjoy and have fun with it.

Definitions

Comment - comments help document a program but do cause the computer to perform any action. They are ignored when the program executes. They are of the form:

  • // this symbol indicates that all that follows the // is a comment
  • A multiline comment starts with /* and ends with */
    /*
     * This is a multiline comment
     */
    

Function - a named section of a program that performs the specific task included between the { and the }.

<iostream.h> - to declare objects that control reading from and writing to the standard streams. This is often the only header you need include to perform input and output from a C++ program.

persistent data - is data that exists after the exit of an application or the turning off of the computer. It exists on a media storage device (e.g., hard disk).




HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript ]

2002 - 2016 All Rights Reserved Total Application Works