Thursday, December 13, 2012

C++ Database Name Search Program: User inputs last, first name, search from a name file, match using string function


/*
PROGRAM: Database Name Search
PURPOSE: Last name and first name input are compared to the records on a namefile.
         If a match is found, then display "Record found at database".
         NOTE: string.find is used here (which is not the best method) just to show
         an example of its use. I know that experienced C++ database programmers have
         their best and most recommended ways for a name search program, you are
         welcome to comment and to share your code (thanks in advance).
LANGUAGE: C++
AUTHOR: eternaltreasures
DATE: 2010 October 2
*/

// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

#define newline '\n'

string recordline;
string last_name_input;
string first_name_input;

int recordnumber = 0;
bool namefound = false;

ifstream recordfile ("namefile.txt");

//Welcome introduction
void welcome_introduction ()
{
cout << newline;
cout << "Welcome to the Records Database Facility!";
cout << newline;
cout << newline;
cout << "Enter name to search: ";
cout << newline;
cout << newline;
cout << "Last name: "; cin >> last_name_input;
cout << "First name: "; cin >> first_name_input;
cout << newline;
}

//Compare the user input last name and first name against the database record file
void stringmatch ()
{
 //location1 and location2 are variables to receive the user's last name and first name
 string::size_type location1 = recordline.find(last_name_input, 0);
 string::size_type location2 = recordline.find(first_name_input, 0);

 if (location1 != string::npos)
    {
     if (location2 != string::npos)
      {
      cout << "Name found at database: ";
      cout << "Record " << recordnumber << " " << recordline;
      namefound = true;
      cout << newline;
      }
     } 
}

//Read the Name Database file
//Check the last name and first name inputs if found on the file (database)
void read_record_file ()
{
 if (recordfile.is_open())
   {
    while (!recordfile.eof() )
     {
      getline (recordfile, recordline);
      recordnumber = recordnumber + 1;
      stringmatch ();
     }
    if (recordfile.eof())
     {
      if (namefound == false)
       cout << "eof: Record not found on database.";
     }
    }   
 else
  {
   cout << "Error opening the file";
   recordfile.close();
  }


int main ()
{
welcome_introduction ();   
read_record_file ();

return 0;
}

No comments:

Post a Comment