Saturday, September 24, 2011

C++ STL UNARY PREDICATE FUNCTIONS

C++ STL UNARY PREDICATE FUNCTIONS TUTORIAL







REVISED: Sunday, March 3, 2013


CONTENTS:
I.   INTRODUCTION
II.  PREDICATE FUNCTIONS
III. WRITING UNARY PREDICATES

YOU WILL LEARN HOW TO:
1. Write STL unary predicates.
2. Use the STL unary predicate functions with arrays.
3. Use the STL unary predicate functions with lists.
4. Use the STL unary predicate functions with vectors.

I. INTRODUCTION


Welcome to the “C++ STL Unary Predicate Function Tutorial.”

II. PREDICATE FUNCTIONS


Predicate functions test the truth or falsity of conditions; for example, an isEmpty function or an isFull function. A binary predicate function takes two arguments, performs a comparison using those two arguments and returns a bool value indicating the result. A unary predicate function takes a single value argument, performs a comparison using that argument and returns a bool value indicating that result.

A. UNARY PREDICATE FUNCTIONS


Examples of the unary predicate functions are: replace_if, remove_if, partition, stable_partition, replace_copy_if, remove_copy_if, count_if, and find_if.


In the STL, instead of seeing unary predicate function you will normally just see the word predicate.


For discussion purposes, lets take a look at the STL count_if( ) function.


The count_if( ) function has three parameters. The first parameter is the starting point. The second parameter is the ending point. The third parameter is the unary predicate which returns the condition you want for inclusion in the count returned by the count_if( ) function.

count_if( ) returns the total of the number of elements that match a unary predicate condition between the starting point and the ending point in a series of elements.

1. ARRAY EXAMPLE


The syntax for instantiating an array object is as follows:

type arrayName [arrayElements];


a. A one-dimensional array name by itself without the elements enclosed by the square brackets is automatically converted to a pointer to the address of the first element of the array. Therefore, the array name A, in the attached array example program, is used for the first parameter.

b. The amount of memory required to store each element of an array is determined by its type. And, all the elements of the array are stored in a contiguous block of memory. Therefore, the sizeof operator is very useful when working with an array. In the const int N = (sizeof(A) / sizeof(A[0])); statement of the following array example program; sizeof( ) divides the number of bytes occupied by the whole A[ ] array by the number of bytes occupied by the first element of the A[ ] array. Because each element in the array occupies the same amount of memory, the result is the number of elements in the A[ ] array. After being computed, the number of elements in the A[ ] array is assigned to the variable N. Using pointer arithmetic, A + N is used for the second parameter.

c. The third parameter is the unary predicate which returns the condition you want for inclusion in the count returned by the count_if( ) function. The attached example program unary predicate function name is isMoreThan30.

The array example program is as follows:

//***********************************
//C++ STL UNARY PREDICATE
//FUNCTIONS TUTORIAL
//Array Example:
//***********************************
#ifndef CALC_ERROR_H
#define CALC_ERROR_H
#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>            
#include <string>
#include <vector>
using namespace std;
#endif 
//CALC_ERROR_H
   
void ClearScreen( ); 
//Clears the screen.
void Pause( );            
//Waits for user response.
bool evenlyDivisibleByTwo(int i);  //Returns true if number
//is an even number.

//***********************************
//Clear Screen.
//***********************************
void ClearScreen( )
{
    system( "CLS" );
    cout << endl << endl << endl;
}

//***********************************
//Pause.
//***********************************
void Pause( )
{
    cout << endl << endl << endl;
    cout << "  ";
    system( "PAUSE" );
}

//***********************************
//Unary Predicate Function:
//Returns true if number is more than
//30.
//***********************************
bool isMoreThan30( int value )
{
   return value >30;
}

//***********************************
// MAIN() FUNCTION.
//***********************************
int main(int argc, char* argv[ ])
{
    ClearScreen( );
    int A[ ] = { 9, 12, 32, 18, 4, 96, 5, 42, 33, 10 };
    const int N = (sizeof(A) / sizeof(A[0]));
    cout << endl << endl;

    cout << "  The " << count_if(A, (A + N), isMoreThan30);

    cout << " numbers more than 30 are: ";
    for( int i = 0; i < N; i++ )
    {
        if (isMoreThan30( A[ i ] ))
        {
            cout << A[ i ] << " ";
        }
    }
      Pause( );
    return EXIT_SUCCESS;
}

2. LIST EXAMPLE:


The syntax for instantiating a list object is as follows:

list <type> objectName;


list is a C++ keyword. The angle brackets contain the word type <type> which is a placeholder for the type of the list you are instantiating. objectName is the name of the list object you are instantiating.

When working with a list the count_if( ) function’s three parameters are as follows:

a. objectName.begin( ) sets the list element starting point.

begin( ) is a function that automatically moves the pointer to the first element of the list.

b. objectName.end( ) sets the list element ending point.

end( ) is a function that automatically works with the begin( ) function to establish a range of list elements which will be tested for the condition of the unary predicate. In this case the range is from the first element of the list to the last element of the list.

c. Unary Predicate


The unary predicate is established by the programmer by writing a Boolean function which returns the appropriate condition for the count_if( ) function. The attached list example program unary predicate function name is isDivisibleByThree.

The list example program is as follows:

//**********************************
//C++ STL UNARY PREDICATE
//FUNCTIONS TUTORIAL
//List Example:
//**********************************
#ifndef CALC_ERROR_H
#define CALC_ERROR_H
#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <list>
#include <sstream>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>            
#include <string>
#include <vector>
using namespace std;
#endif
//CALC_ERROR_H
   
void ClearScreen( );  
//Clears the screen.
void Pause( );             
//Waits for user response.
bool evenlyDivisibleByTwo(int i);  //Returns true if number is
//an even number.

//**********************************
//Clear Screen.
//**********************************
void ClearScreen( )
{
    system( "CLS" );
    cout << endl << endl << endl;
}

//**********************************
//Pause.
//**********************************
void Pause( )
{
    cout << endl << endl << endl;
    cout << "  ";
    system( "PAUSE" );
}

//**********************************
//Unary Predicate Function:
//Returns true if number is more than
//30.
//**********************************
//bool isMoreThan30( int value )
//{
//   return value > 30;
//}

//**********************************
//Unary Predicate Function:
//Returns true if number is
//divisible by 3.
//**********************************
bool isDivisibleBy3(int i)
{
  if((i%3) == 0) return true;
   
  return false;
}

//**********************************
// MAIN() FUNCTION.
//**********************************
int main(int argc, char* argv[ ])
{
    ClearScreen( );

//Instantiate object myList.
    list<int> myList;

//Insert list elements.
    for ( int i=6; i<=20; ++i )
    {
        myList.push_back( i );
        if ( isDivisibleBy3( i ) )
        {
            cout << "  " << i;
        }
    }

//Instantiate iterator.
    list<int>::iterator myIt;
   
    cout << "  are the " << count_if(myList.begin( ), myList.end( ), isDivisibleBy3);
    cout << " numbers divisible by 3.  ";
 
     Pause( );
    return EXIT_SUCCESS;
}

3. VECTOR EXAMPLE


The syntax for instantiating a vector object is as follows:

vector <type> objectName;


vector is a C++ keyword. The angle brackets contain the word type <type> which is a placeholder for the type of the vector you are instantiating. objectName is the name of the vector object you are instantiating.

When working with a vector the count_if( ) function’s three parameters are as follows:

a. objectName.begin( ) sets the vector element starting point.

begin( ) is a function that automatically moves the pointer to the first element of the vector.

b. objectName.end( ) sets the vector element ending point.

end( ) is a function that automatically works with the begin( ) function to establish a range of vector elements which will be tested for the condition of the unary predicate. In this case the range is from the first element of the vector to the last element of the vector.

c. Unary Predicate


The unary predicate is established by the programmer by writing a Boolean function which returns the appropriate condition for the count_if( ) function. The attached vector example program unary predicate function name is evenlyDivisibleByTwo.

The vector example program is as follows:

//**********************************
//C++ STL PREDICATE
//FUNCTIONS TUTORIAL
//Vector Example:
//**********************************
#ifndef CALC_ERROR_H
#define CALC_ERROR_H
#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>            
#include <string>
#include <vector>
using namespace std;
#endif
//CALC_ERROR_H
   
void ClearScreen( ); 
//Clears the screen.
void Pause( );            
//Waits for user response.
bool evenlyDivisibleByTwo(int i);  //Returns true if number
//is an even number.

//**********************************
//Clear Screen.
//**********************************
void ClearScreen( )
{
    system( "CLS" );
    cout << endl << endl << endl;
}

//**********************************
//Pause.
//**********************************
void Pause( )
{
    cout << endl << endl << endl;
    cout << "  ";
    system( "PAUSE" );
}

//********************************** 
//Unary Predicate Function:
//Returns true if number is an even
//number.
//********************************** 
bool evenlyDivisibleByTwo( int i )
{
  return !( i%2 );
}

//********************************** 
// MAIN() FUNCTION.
//********************************** 
int main(int argc, char* argv[ ])
{
    ClearScreen( );

    vector< int > VO;

    int i;

    for( i = 1; i < 40; i++ )
    VO.push_back( i );

    cout << "  The even numbers are: ";
    for(i = 0; i < VO.size( ); i++)
    {
        if (evenlyDivisibleByTwo( VO[ i ] ))
        {
            cout << VO[ i ] << " ";
        }
    }
    cout << endl << endl;

    i = count_if(VO.begin( ), VO.end( ), evenlyDivisibleByTwo);
    cout << "  " << i << " TOTAL" << endl;

    Pause( );

    return EXIT_SUCCESS;
}

III. WRITING UNARY PREDICATES


The following must be taken into consideration when writing predicates:

A. A unary predicate is called like a function; therefore, a unary predicate must be callable.

B. A unary predicate must accept one argument and return a value that is convertible to Boolean. One argument is supplied when the predicate is called. The return value is used as a conditional expression and must be convertible to type bool.

C. The predicate must not modify its argument. A unary predicate must not modify the elements in the input sequence that it receives as an argument. The unary predicate can inspect the sequence elements, but it must not modify them.

D. Unary predicates logic must not be dependent on the order in which sequence elements are supplied to it.


YOU HAVE LEARNED HOW TO:
1. Write STL unary predicates.
2. Use the STL unary predicate functions with arrays.
3. Use the STL unary predicate functions with lists.
4. Use the STL unary predicate functions with vectors.

Elcric Otto Circle






-->


-->


-->






How to Link to My Home Page
It will appear on your website as:

"Link to: ELCRIC OTTO CIRCLE's Home Page"




C++ FILE PROCESSING...

C++ FILE PROCESSING TUTORIAL







REVISED: Sunday, March 3, 2013




CONTENTS:
I. ASSUMPTIONS
II. INTRODUCTION
III. VOCABULARY
IV. CREATING A SEQUENTIAL FILE

YOU WILL LEARN:
1. File processing vocabulary.
2. How to create a sequential file.

I. ASSUMPTIONS


I assume you have a C++ compiler and you want to learn about C++ file processing.

II. INTRODUCTION 


Welcome to the “C++ File Processing Tutorial.”

Please copy and paste the two following example programs into a file your compiler can read. Then build, compile, and debug the two example programs. Following along, back and forth, between the tutorial and your copy of the two example programs will help you understand the example program's functionality.

//**********************************
//C++ Beginner File Processing
//Tutorial Sequential File
//**********************************
#ifndef CALC_ERROR_H
#define CALC_ERROR_H
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::fixed;
using std::exit;
using std::ifstream;
using std::ios;
using std::left;
using std::right;
using std::ofstream;
using std::setw;
using std::showpoint;
using std::setprecision;
using std::string;

#endif  //CALC_ERROR_H

class CAccountsPayable
{
    public:

               CAccountsPayable();
        void   m_CreateSequentialFile();
        void   m_ReadSequentialFile();
               ~CAccountsPayable();
    private:

        int account;
        char   lastName[ 15 ];
        char   firstName[ 10 ];
        double balance;
 
};

CAccountsPayable::CAccountsPayable()  //Constructor.
{

}

//**********************************
//Creates a sequential file.
//**********************************
void CAccountsPayable::m_CreateSequentialFile()
{
    ofstream outCustomerFile("CustomerFile.dat", ios::out);  
//File created for output.
//Two arguments passed to
//constructor: filename, and
//file open mode.
//ios::out output mode to truncate
//an existing file and output
//new data to the file.
//ios::out creates a new file
//if the file does not already exist.
//By default ofstream oubjects
//are opened for output; therefore,
//ios::out was not needed.
//ios::app append mode
//to append data to the end
//of an existing file.

    int account      = 0;
    char   lastName[ 15 ]  = {" "};
    char   firstName[ 10 ] = {" "};
    double balance       = 0.0;
    int choice        = 0;
    bool   exitt           = false;
   
    if (outCustomerFile.is_open())
//Checks to see if file is open.
    {
        system( "CLS" );
        cout << endl << endl << endl;
        cout << "  C++ Beginner File Processing Tutorial" << endl << endl;
        cout << "          Sequential File" << endl << endl;

        do
        {
            cout << endl << endl << endl;
            cout << "  Please enter customer account number." << endl << endl;
            cout << "  Any number from 1 to 100, for example, 1 " << endl << endl;
            cout << "  and then press Enter => ";
            cin  >> account;
            cout << endl << endl << endl;
            cout << "  You entered " << account;
            cout << endl << endl << endl;
            cout << "  ";
            system ("PAUSE");

            system( "CLS" );
            cout << endl << endl << endl;
            cout << "  Please enter customer last name." << endl << endl;
            cout << "  Maximum 15 characters, for example Jones" << endl << endl;
            cout << "  and then press Enter => ";
            cin  >> lastName;
            cout << endl << endl << endl;
            cout << "  You entered " << lastName;
            cout << endl << endl << endl;
            cout << "  ";
            system ("PAUSE");

            system( "CLS" );
            cout << endl << endl << endl;
            cout << "  Please enter customer first name." << endl << endl;
            cout << "  Maximum 10 characters, for example Roy" << endl << endl;
            cout << "  and then press Enter => ";
            cin  >> firstName;
            cout << endl << endl << endl;
            cout << "  You entered " << firstName;
            cout << endl << endl << endl;
            cout << "  ";
            system ("PAUSE");

            system( "CLS" );
            cout << endl << endl << endl;
            cout << "  Please enter customer account balance." << endl << endl;
            cout << "  for example, 1000 " << endl << endl;
            cout << "  and then press Enter => ";
            cin  >> balance;
            cout << endl << endl << endl;
            cout << "  You entered " << balance;
            cout << endl << endl << endl;
            cout << "  ";
            system ("PAUSE");

            outCustomerFile << account << " " << lastName << " " << firstName << " " << balance << endl; 
//One record of four fields each
//separated by a blank space.

            system( "CLS" );
            cout << endl << endl << endl;
           
            cout << "  Type the number 1 and press return ";
            cout << "to enter another record.  " << endl << endl;
            cout << "  Type 0 and press return to exit. ==> ";
            cin >> choice;
            if ( choice == 0 )
            {
                break;
            }
            if ( choice == 1 )
                exitt = false;
            else
            {
                exitt = true;
            }
        }while( exitt == false );

            outCustomerFile.close(); 
//Closes file.
    }
    else
    {
        if(!outCustomerFile)
        {
            system( "CLS" );
            cout << endl << endl << endl;
            cerr << "  Unable to open file.";
            cout << endl << endl << endl;
            cout << "  ";
            system ("PAUSE");
            exit(1);
//Argument 0 is a normal exit,
//any other value is an error exit.
        }
    }
}

//**********************************
//Reads a sequential file.
//**********************************
void CAccountsPayable::m_ReadSequentialFile( )
{
    ifstream inCustomerFile("CustomerFile.dat", ios::in);  
//File created for input.
//Two arguments passed to
//constructor: filename, and
//file input mode.
//ios::in input mode to open an
//existing file for input from the
//file into the program.
//ios::in results in an error message
//if the file does not already exist.
   
    int account    = 0;
    char   lastName[15]  = {" "};
    char   firstName[10] = {" "};
    double balance     = 0.0;
   
    if (inCustomerFile.is_open( ))
//Checks to see if file is open.
    {
        while( inCustomerFile >> account >> lastName >> firstName >> balance )
        {
            system ("CLS");
            cout << endl << endl << endl;
            cout << "  Account Number:  " << account   << endl << endl;
            cout << "  Last Name:    " << lastName  << endl << endl;
            cout << "  First Name:      " << firstName << endl << endl;
            cout << "  Account Balance: " << balance   << endl << endl;  //One record.
           
            cout << endl << endl << endl;
            cout << "  ";
            system ("PAUSE");
        }

        inCustomerFile.close( );
//Closes file.
    }
    else
    {
        if(!inCustomerFile)
        {
            system( "CLS" );
            cout << endl << endl << endl;
            cerr << "  Unable to open file.";
            cout << endl << endl << endl;
            cout << "  ";
            system ("PAUSE");
            exit(1); 
//Argument 0 is a normal exit,
//any other value is an error exit.
        }
    }
}

CAccountsPayable::~CAccountsPayable()
//Destructor.
{

}

//**********************************
// MAIN( ) FUNCTION.
//**********************************
int main(int argc, char* argv[ ])
{
    int  choice   = 0;
    bool    exit     =  false;

//**********************************
   
    CAccountsPayable OPencil;

    do
    {
        OPencil.m_CreateSequentialFile( );
        OPencil.m_ReadSequentialFile( );

//**********************************
        system( "CLS" );
        cout << endl << endl << endl;
        cout << "  Type the number 1 and press return ";
        cout << "to run the program again.  " << endl << endl;
        cout << "  Type 0 and press return to exit. ==> ";
        cin >> choice;
        if ( choice == 0 )
        {
            EXIT_SUCCESS;
        }
        if ( choice == 1 )
            exit = false;
        else
        {
            exit = true;
        }
    }while( exit == false );

    OPencil.~CAccountsPayable();

    return EXIT_SUCCESS;
}

//**********************************
//C++ File Processing Tutorial
//Random Access File
//**********************************
#ifndef CALC_ERROR_H
#define CALC_ERROR_H
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::fixed;
using std::exit;
using std::ifstream;
using std::ios;
using std::left;
using std::right;
using std::ofstream;
using std::ostream;
using std::setw;
using std::showpoint;
using std::setprecision;
using std::string;

#endif  //CALC_ERROR_H

class CAccountsPayable
{
    public:

//Constructor.
       CAccountsPayable( int = 0, string = "", string = "", double = 0.0 );

//Accessor function for account number.
       void m_SetAccountNumber( int );
       int  m_GetAccountNumber( ) const;

//Accessor function for last name.
       void m_SetLastName( string );
       string m_GetLastName( ) const;

//Accessor function for first name.
       void m_SetFirstName( string );
       string m_GetFirstName( ) const;

//Accessor function for balance.
       void m_SetBalance( double );
       double m_GetBalance( ) const;

//Destructor.    
       ~CAccountsPayable( );

    private:

        int accountNumber;
        char   lastName[ 15 ];
        char   firstName[ 10 ];
        double balance;
};

//**********************************
//Constructor
//**********************************
CAccountsPayable::CAccountsPayable(int accountNumberValue,
    string lastNameValue, string firstNameValue, double balanceValue )
{
    m_SetAccountNumber( accountNumberValue );
    m_SetLastName( lastNameValue );
    m_SetFirstName( firstNameValue );
    m_SetBalance( balanceValue );
}

//**********************************
//Get account number value.
//**********************************
int  CAccountsPayable::m_GetAccountNumber( ) const
{
    return accountNumber;
}

//**********************************
//Set account number value.
//**********************************
void CAccountsPayable::m_SetAccountNumber( int accountNumberValue )
{
    accountNumber = accountNumberValue;
}

//**********************************
//Get last name value.
//**********************************
string  CAccountsPayable::m_GetLastName( ) const
{
    return lastName;
}

//**********************************
//Set last name value.
//**********************************
void CAccountsPayable::m_SetLastName( string lastNameString )
{
    const char *lastNameValue = lastNameString.data( );
    int length = lastNameString.size( );
    length = ( length < 15 ? length : 14 );
    strncpy_s( lastName, lastNameValue, length );
    lastName[ length ] = '\0';
}

//**********************************
//Get first name value.
//**********************************
string  CAccountsPayable::m_GetFirstName( ) const
{
    return firstName;
}

//**********************************
//Set first name value.
//**********************************
void CAccountsPayable::m_SetFirstName( string firstNameString )
{
    const char *firstNameValue = firstNameString.data( );
    int length = firstNameString.size( );
    length = ( length < 10 ? length : 9 );
    strncpy_s( firstName, firstNameValue, length );
    firstName[ length ] = '\0';
}

//**********************************
//Get balance value.
//**********************************
double CAccountsPayable::m_GetBalance( ) const
{
    return balance;
}

//**********************************
//Set balance value.
//**********************************
void CAccountsPayable::m_SetBalance( double balanceValue )
{
    balance = balanceValue;
}

//**********************************
//Destructor
//**********************************
CAccountsPayable::~CAccountsPayable( )
{

}

//**********************************
// MAIN() FUNCTION.
//**********************************
int main(int argc, char* argv[ ])
{
    int  choice =   0;
    bool    exitt    =  false;
//**********************************
       
    do
    {
        system("CLS");
        cout << endl << endl << endl;
        cout << " C++ Beginner File Processing Tutorial   "  << endl << endl;
        cout << "   ---------------------------------------  "  << endl << endl;
        cout << " 0  Quit, exits program.              "  << endl << endl;
        cout << " 1  Create Random Access File:          "  << endl;
        cout << "    Writes Fixed Length Records To File  "  << endl << endl;
        cout << " 2  Write To Random Access File        "  << endl << endl;
        cout << " 3  Read Random Access File Sequentially "  << endl << endl << endl;
                       
        cout << endl << endl;
        cout << " Please type a number from 0 to 3 " << endl << endl;
        cout << " then press Enter ==> ";

        cin >> choice;

        switch(choice) 
//start switch
        {
            case (0):
                exitt    =  true;
                return EXIT_SUCCESS;
                break;

            case (1):
//**********************************
//Writes fixed length records to
//random access file.         //**********************************
            {
                ofstream outAccountsPayable( "AccountsPayable.dat",
                ios::out | ios::binary );

                if ( !outAccountsPayable )
                {
                    system("CLS");
                    cout << endl << endl << endl;
                    cerr << "  File could not be opened." << endl;
                    cout << endl << endl << endl;
                    cout << "  ";
                    system("PAUSE");
                    exit( 1 );

//Instantiates object
//OBlankAccountsPayable of type
//CAccountsPayable.
                    CAccountsPayable OBlankAccountsPayable;

                    for ( int i = 0; i < 100; i++ )
                    {
                        outAccountsPayable.write( reinterpret_cast
                        < const char * > ( &OBlankAccountsPayable ),
                        sizeof ( CAccountsPayable ) );
                    }
                }
            system("CLS");
            cout << endl << endl << endl;
            cout << "  Congratulations you successfully created a random access file! " << endl << endl << endl;
            cout << endl << endl << endl;
            cout << "  ";
            system ("PAUSE");

            }

//**********************************
                break;

            case (2):

//**********************************
//Writes to the random access file.            //**********************************
            {
                int accountNumber;
                char   lastName[ 15 ];
                char   firstName[ 10 ];
                double balance;

                fstream outAccountsPayable( "AccountsPayable.dat",
                ios::in | ios::out |ios::binary );
               
                if ( !outAccountsPayable )
                {
                    system("CLS");
                    cout << endl << endl << endl;
                    cerr << "  File could not be opened." << endl;
                    cout << endl << endl << endl;
                    cout << "  ";
                    system("PAUSE");
                    exit( 1 );
                }

                system("CLS");
                cout << endl << endl << endl;
                cout << "  Please enter customer account number." << endl << endl;
                cout << "  Enter a number from 1 to 100 " << endl << endl;
                cout << "  then press Enter => ";

//Instantiates object OCustomer
//of type CAccountsPayable.
                CAccountsPayable OCustomer;

                cin >> accountNumber;
                cout << endl << endl << endl;
                cout << "  You entered " << accountNumber;
                cout << endl << endl << endl;
                cout << "  ";
                system ("PAUSE");

                if( accountNumber > 0 && accountNumber <= 100 )
                {
                    system( "CLS" );
                    cout << endl << endl << endl;
                    cout << "  Please enter customer last name." << endl << endl;
                    cout << "  Maximum 15 characters, for example Jones" << endl << endl;
                    cout << "  and then press Enter => ";
                    cin  >> setw( 15 ) >> lastName;
                    cout << endl << endl << endl;
                    cout << "  You entered " << lastName;
                    cout << endl << endl << endl;
                    cout << "  ";
                    system ("PAUSE");

                    system( "CLS" );
                    cout << endl << endl << endl;
                    cout << "  Please enter customer first name." << endl << endl;
                    cout << "  Maximum 10 characters, for example Roy" << endl << endl;
                    cout << "  and then press Enter => ";
                    cin  >> setw( 10 ) >> firstName;
                    cout << endl << endl << endl;
                    cout << "  You entered " << firstName;
                    cout << endl << endl << endl;
                    cout << "  ";
                    system ("PAUSE");

                    system( "CLS" );
                    cout << endl << endl << endl;
                    cout << "  Please enter customer account balance." << endl << endl;
                    cout << "  for example, 1000 " << endl << endl;
                    cout << "  and then press Enter => ";
                    cin  >> balance;
                    cout << endl << endl << endl;
                    cout << "  You entered " << balance;
                    cout << endl << endl << endl;
                    cout << "  ";
                    system ("PAUSE");
                    OCustomer.m_SetAccountNumber( accountNumber );
                    OCustomer.m_SetLastName( lastName );
                    OCustomer.m_SetFirstName( firstName );
                    OCustomer.m_SetBalance( balance );

                    outAccountsPayable.seekp( ( OCustomer.m_GetAccountNumber( ) - 1 ) *
                        sizeof( CAccountsPayable ) );

                    outAccountsPayable.write( reinterpret_cast< const char * > ( &OCustomer ),
                        sizeof( CAccountsPayable ) );
                }
            }
//**********************************
                break;

            case (3):
//**********************************
//Read random access file sequentially.
//**********************************
            {
                ifstream inAccountsPayable( "AccountsPayable.dat",
                ios::in | ios::binary );
               
                if ( !inAccountsPayable )
                {
                    system("CLS");
                    cout << endl << endl << endl;
                    cerr << "  File could not be opened." << endl;
                    cout << endl << endl << endl;
                    cout << "  ";
                    system("PAUSE");
                    exit( 1 );
                }

                cout << left << setw( 10 ) << "Account"
                     << setw ( 16 ) << "Last Name" << left
                     << setw ( 11 ) << "First Name"
                     << setw ( 10 ) << right << "Balance" << endl;

//Instantiates object OCustomer
//of type CAccountsPayable.
                CAccountsPayable OCustomer;

                inAccountsPayable.read( reinterpret_cast< char * >
                    ( &OCustomer ), sizeof( CAccountsPayable ) );

                while ( inAccountsPayable && !inAccountsPayable.eof( ) )
                {
                    if ( OCustomer.m_GetAccountNumber( ) != 0 )
                    {
                           system("CLS");
                           cout << endl << endl << endl;
                           cout << "  ";

                      cout << left << setw( 10 ) << OCustomer.m_GetAccountNumber( )
                           << setw ( 16 ) << OCustomer.m_GetLastName( ) << left
                           << setw ( 11 ) << OCustomer.m_GetFirstName( )
                           << setw ( 10 ) << setprecision( 2 ) << right << fixed
                           << showpoint << OCustomer.m_GetBalance( ) << endl;

                           cout << endl << endl << endl;
                           cout << "  ";
                           system("PAUSE");
                    }
               
                    inAccountsPayable.read( reinterpret_cast< char * >
                        ( &OCustomer ), sizeof( CAccountsPayable ) );
                }
                   
            }

//**********************************
                break;

            default:
                cout << endl << endl << endl;
                cout << "Switch default error message! ";
                cout << endl << endl << endl;
                system("PAUSE");
                break;
        }

    }while( exitt == false );

    return EXIT_SUCCESS;
}

III. VOCABULARY

A. What is a bit?


A bit is a binary digit that can assume one of two values, 0 or 1. A bit is the smallest data item supported by computers.

B. What is a byte?

A byte is eight bits.

C. What is a character?


Digits, letters, and special symbols are referred to as characters.

D. What is a field?


A field is composed of characters that convey meaning.

E. What is a record?


A record is represented as a class in C++ and is composed of fields called data members.

F. What is a file?


Files you create with your editor are called source files. Most C++ compilers do not care what extension you give your source file, .cpp is normally the default. After your source file is compiled an object file is produced with an .obj or .o extension, C++ executable .exe extension programs are created by linking one or more object files with one or more libraries. Libraries are linkable files supplied with your compiler.

The files we will be discussing in this tutorial are the text files and binary files that store data which can be retrieved for processing when needed.

A storage file is a group of related records. C++ views each file as a sequence of bytes. When a file is opened an object is created and a stream is associated with that object. If the file can support position requests, opening the file also initializes the file position indicator to the start of the file. To perform file processing in C++, header files <iostream> and <fstream> must be included to provide communications between a program and a file or device.

Standard input, standard output, and standard error output are three files that are connected to the console and opened automatically when a program is started. The file pointers stdin, stdout, and stderr are also automatically provided for these three files respectively.

G. What is a record key?


A record key uniquely identifies a record.

H. What is a database?


A group of related files are stored in a database.

I. What is a Database Management System (DBMS)?


A DBMS is a collection of programs designed to create and manage a database.

IV. CREATING A SEQUENTIAL FILE

Step 1 Create A Stream:


Before you can use the member functions of a class in your program you have to create a stream by instantiating or declaring an object of that class in your program. The class for output is ofstream. You can use any object name you want to use.

The syntax for instantiating an object of the ofstream class is as follows:

ofstream object_name;

Step 2 Associate Or Link That Object With A File


After you create a stream by instantiating an object of the class in your program you have to associate or link that object with a file. You can use the open( ) function to associate the instantiated object with a file.

The complete detailed syntax for the prototype of an output file is as follows:

void ofstream::open(const char *filename, ios::openmode mode = ios::out | ios::trunc);


When the ofstream object is instantiated and associated with a file the ofstream object’s constructor opens the file.

After the stream object is associated with a file, the file can be used the same as any other stream object.


YOU HAVE LEARNED:
1. File processing vocabulary.
2. How to create a sequential file.

Elcric Otto Circle



-->

-->

-->








How to Link to My Home Page



It will appear on your website as:

"Link to: ELCRIC OTTO CIRCLE's Home Page"