Slide 6.1: Record access
Slide 6.3: A sequential search
Home

A C++ Program for Sequential Searches


The C++ program below shows how to implement the previous interface. It uses the command
   if ( strcmp(b.ISBN, argv[2] ) == 0)
to find whether or not the key is matched.

~wenchen/public_html/cgi-bin/351/week6/Sequential.cpp

#include <fstream> #include <iostream> #include <cstdlib> #include <cstring> using namespace std;

class Book { public: char title[129]; char ISBN[13]; char price[8]; int quantity; };

istream& operator>> ( istream& stream, Book& b ) { char temp[6]; stream.getline( b.title, 128, '|' ); if ( strlen( b.title ) == 0 ) return( stream ); stream.getline( b.ISBN, 12, '|' ); stream.getline( b.price, 8, '|' ); stream.getline( temp, 6, '|' ); b.quantity = atoi( temp ); return( stream ); }

int main( int argc, char* argv[ ] ) { char command[128]; fstream file; Book b; // Compose the lynx command. strcpy( command, "lynx -dump -source " ); strcat( command, argv[1] ); strcat( command, " > input.txt" ); system( command ); file.open( "input.txt", fstream::in ); cout << "<table width='90%' bgcolor='#EDF3FE' border='2'>"; cout << "<tr><th>Title</th><th>ISBN</th>"; cout << "<th>Price</th><th>Quantity</th></tr>"; // Perform the sequential search. while ( true ) { file >> b; if ( strlen( b.title ) == 0 ) break; else if ( strcmp( b.ISBN, argv[2] ) == 0 ) { cout << "<tr><td>" << b.title; cout << "</td><td align='center'>" << b.ISBN; cout << "</td><td align='center'>" << b.price; cout << "</td><td align='center'>" << b.quantity; cout << "</td></tr>"; } } cout << "</table></center>"; file.close( ); }