Search book by its author from 1st record to last
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 10 of 10

Thread: Search book by its author from 1st record to last

  1. #1
    Join Date
    May 2012
    Posts
    10

    Search book by its author from 1st record to last

    Hey everyone! i stuck here with a thing. I use this code to search a book by its author. I have used the approach of bubble sorting then binary searching.

    Alright, now this is what i have. what i want to do now is to search a particular BOOK by its author without using the bubble sorting or binary searching method and instead search all the records one at a time, from start till the end for its author. I think the improved approach will make the coding a lot shorter than it is now




    Code:
    //***************************************************************
    //                   HEADER FILE USED IN PROJECT
    //****************************************************************
    
    #include<fstream> 
    #include<conio.h>
    #include<stdio.h>
    #include<process.h>
    #include<string.h>
    #include<iomanip>
    #include<iostream>
    
    
    using namespace std;
    
    class BOOK
    {
    public:
    	char ID[6];
    	char Content[50];
    	char AUTHOR[20];
    	char Book[20];
      
    	void create_book()// create new BOOK
    	{
    		cout<<"\nNEW BOOK ENTRY...\n";
    		cout<<"\nEnter The BOOK ID.";
    		gets(ID);
    		cout<<"\n\nEnter BOOK NAME ";
    		gets(Content);
    		cout<<"\n\nEnter The AUTHOR's Name ";
    		gets(AUTHOR);
    		cout<<"\n\nEnter The Source Book ";
    		gets(Book);
    		cout<<"\n\n\nBOOK Created..";
    		getch();
    	}
    
    	
    	
    	void report()
    	{cout<<ID<<setw(10)<<Content<<setw(30)<<AUTHOR<<setw(20)<<Book<<endl;} //setw--> set width
    
    	void Copy(BOOK hd){ //  this function copies whole record
    		strcpy(ID,(hd.ID)); //copy BOOK ki id
    		strcpy(AUTHOR,(hd.AUTHOR)); // copy BOOK ka AUTHOR
    		strcpy(Book,(hd.Book));
    		strcpy(Content,(hd.Content));
    
    	}
    
    };         //class ends here
    
    void SwapBOOK(BOOK &hd1, BOOK &hd2){ //swaps position of BOOK1 with BOOK2
    
    	BOOK Temp;            
    
    	Temp.Copy(hd1);  //BOOK1 ko temp main copy kiya
    	hd1.Copy(hd2);   //BOOK2 ko BOOK1 main copy kiya (now BOOK2 has moved to the place of BOOK1)
    	hd2.Copy(Temp);  //BOOK1 ko finalyy BOOK2 ki jaga per copy ker diya
    }
    
    
    //***************************************************************
    //    	global declaration for stream object, object
    //****************************************************************
    fstream fp; // fstream provides an interface to read and write data from files as input/output streams.
    ofstream ofp; // ofstream provides an interface to write data to files as output streams
    BOOK hd[1000]; //array of 1000 BOOK
    int countBOOK=0; // initially there are zero aBOOK in the program
    
    void ReportAll(){ // this function outputs a
    	system("cls");
    	for(int i=0;i<countBOOK;i++){
    		hd[i].report();
    
    	}
    	getche();
    	
    }
    
    
    void writeAllBOOK()
    {
    	char ch;
    	ofp.open("BOOK.dat",ios::trunc); // purani file (BOOK.dat) del ker k poora naya content overwrite ker do in new file
    	//If the file opened for output operations already existed before, its previous content is deleted and replaced by the new one.
    		system("cls");
    		for(int i=0; i < countBOOK;i++){
    
    			ofp.write((char*)&(hd[i]),sizeof(BOOK)); // hd[i] ko char samaj k write ker do BOOK
    		
    		}
    
    		ofp.flush(); // abhi write ker do ... buffer istimal mat kero
        ofp.close();// close file
    }
    
    BOOK temp;
    
    void LoadAllBOOK() 
    {
    	system("cls");
    	fp.open("BOOK.dat",ios::in);// read file
    	if(!fp) // if file doesnt opens
    	{
    		cout<<"ERROR!!! FILE COULD NOT BE OPEN ";
           		getch(); // character lo
    			countBOOK =0;
           		return; // or waapis peechhay walay menu main chal do
         	}
    
    	int i=0;
    		while(fp.read((char*)&temp,sizeof(BOOK))) // file say  BOOK k siz ko as a string read ker raha hai and loading to  memory 
    	{
    		hd[i++].Copy( temp); // copying BOOK to main array
    	}
    		countBOOK=i; // jitni dafa ye kaam ho 'count BOOK' ko utni dafa increment day do
         	fp.close(); // close file
         	getch();
    }
    
    //***************************************************************
    //    	SORT AND SEARCH BY AUTHOR (START)
    //****************************************************************
    
    
    
    void SortByAUTHOR() // bubble sort
    {
    	for(int i=0; i< countBOOK-1; i++){
    		for(int j=0; j <countBOOK-1; j++){
    			if(strcmp(hd[j].AUTHOR,hd[j+1].AUTHOR)>0) 
    				SwapBOOK(hd[j],hd[j+1]); // if above condition is satisfied, then call 'swapBOOK' function which is defined by us
    		}
    	}
    
    
    }
    
    //////////////////////////////////////////////////////////////////
    void SearchBetweenIndex(int IndexA, int IndexB, char* AUTHOR)
    {
    	if(IndexA > IndexB){
    		int temp;
    		temp = IndexA;
    		IndexA = IndexB;
    		IndexB= temp;
    	}
    
    	for(int i = IndexA; i <= IndexB;i++){
    		if(strcmp(hd[i].AUTHOR,AUTHOR)==0)
    			hd[i].report();
    	}
    
    	getch();
    }
    
    /////////////////////////////////////////////////////////////////////
    
    void ListByAUTHOR(char* AUTHOR){ //search by AUTHOR 	
    	int PreviousIndex = 0; // first 
    
    	int StartIndex =0 , EndIndex = countBOOK-1;
    	
    	int i=2;
    	while(1==1){
    		int CurrentIndex=(EndIndex+StartIndex)/2; //start searching from the mid position
    		if(strcmp(hd[CurrentIndex].AUTHOR, AUTHOR) > 0){ 
    			PreviousIndex = EndIndex;
    			EndIndex = CurrentIndex;
    		}else if(strcmp(hd[CurrentIndex].AUTHOR, AUTHOR) < 0){
    			PreviousIndex = StartIndex;
    			StartIndex = CurrentIndex;
    		}else
    			{
    				SearchBetweenIndex(StartIndex, EndIndex, AUTHOR);
    				break;
    			}
    
    		if(CurrentIndex == PreviousIndex)
    			break;
    	
    		
    
    	}
    
    }
    
    
    /////////////////////////////////////////////////////////////////////
    
    void SortAndSearchByAUTHOR(){ // INPUT AUTHOR SEARCH CRITERIA
    	system("cls");
    	char str[50];
    	cout << "Enter the Search Criteria for AUTHOR ";
    	gets(str);
    	SortByAUTHOR(); // CALL THIS FUNCTION
    	ListByAUTHOR(str); // CALLL THIS FUNCTION
    
    }
    
    //***************************************************************
    //    	SORT AND SEARCH BY AUTHOR ENDS
    //****************************************************************
    
    
    void main()
    {
    	char ch;
    	LoadAllBOOK();
    	do
    	{
    		system("cls");
    		cout<<"\n\n\n\tMAIN MENU";
    		cout<<"\n\n\t01. Create BOOK";
    		cout<<"\n\n\t02. SORT And Search By AUTHOR";
    		cout<<"\n\n\t03. lIST ALL ABOOK";
    	  	cout<<"\n\n\t04. EXIT";
    	  	cout<<"\n\n\tPlease Select Your Option (1-4) ";
    	  	ch=getche();
    	  	switch(ch)
    	  	{
    			case '1':system("cls");
    				hd[countBOOK].create_book();
    				countBOOK++;
    			   	 break;
    		  	case '2':
    				SortAndSearchByAUTHOR();
    			    	 break;
    		    case '3':
    				ReportAll();
    				 break;
    		  	case '4':
    				writeAllBOOK();
    				exit(0);
    		  	default :cout<<"\a";
    		}
        	}while(ch!='4');
    }

  2. #2
    Join Date
    May 2012
    Posts
    10

    Re: Search book by its author from 1st record to last

    basically this is the sorting and searching code i have used and want to replace

    Code:
    void SortByAUTHOR() // bubble sort
    {
    	for(int i=0; i< countBOOK-1; i++){
    		for(int j=0; j <countBOOK-1; j++){
    			if(strcmp(hd[j].AUTHOR,hd[j+1].AUTHOR)>0) 
    				SwapBOOK(hd[j],hd[j+1]); // if above condition is satisfied, then call 'swapBOOK' function which is defined by us
    		}
    	}
    
    
    }
    
    //////////////////////////////////////////////////////////////////
    void SearchBetweenIndex(int IndexA, int IndexB, char* AUTHOR)
    {
    	if(IndexA > IndexB){
    		int temp;
    		temp = IndexA;
    		IndexA = IndexB;
    		IndexB= temp;
    	}
    
    	for(int i = IndexA; i <= IndexB;i++){
    		if(strcmp(hd[i].AUTHOR,AUTHOR)==0)
    			hd[i].report();
    	}
    
    	getch();
    }
    
    /////////////////////////////////////////////////////////////////////
    
    void ListByAUTHOR(char* AUTHOR){ //search by AUTHOR 	
    	int PreviousIndex = 0; // first 
    
    	int StartIndex =0 , EndIndex = countBOOK-1;
    	
    	int i=2;
    	while(1==1){
    		int CurrentIndex=(EndIndex+StartIndex)/2; //start searching from the mid position
    		if(strcmp(hd[CurrentIndex].AUTHOR, AUTHOR) > 0){ 
    			PreviousIndex = EndIndex;
    			EndIndex = CurrentIndex;
    		}else if(strcmp(hd[CurrentIndex].AUTHOR, AUTHOR) < 0){
    			PreviousIndex = StartIndex;
    			StartIndex = CurrentIndex;
    		}else
    			{
    				SearchBetweenIndex(StartIndex, EndIndex, AUTHOR);
    				break;
    			}
    
    		if(CurrentIndex == PreviousIndex)
    			break;
    	
    		
    
    	}
    
    }
    
    
    /////////////////////////////////////////////////////////////////////
    
    void SortAndSearchByAUTHOR(){ // INPUT AUTHOR SEARCH CRITERIA
    	system("cls");
    	char str[50];
    	cout << "Enter the Search Criteria for AUTHOR ";
    	gets(str);
    	SortByAUTHOR(); // CALL THIS FUNCTION
    	ListByAUTHOR(str); // CALLL THIS FUNCTION
    
    }

  3. #3
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,205

    Re: Search book by its author from 1st record to last

    What's your question?

    Sorting and binary searching will be much more efficient with a large dataset. While you want to write concise code, favoring small code over efficient isn't usually a good idea.

    A better approach would be just to sort your list as you build it. When somebody adds a book, use a binary search to find the appropriate place to add it. Your list will be sorted without an explicit sort function.

    You certainly don't want to sort every time somebody does a search. Once you sort it, it should stay sorted.

  4. #4
    Join Date
    May 2012
    Posts
    10

    Re: Search book by its author from 1st record to last

    i have seen this version which resembles mine. can anyone change it to my requirements please?


    Code:
    struct book // declare book class
    {
    	int no;
    	string author; // type name of string
    	string book;	 // type name of string
    	string topic;	// type name of string
    	string genre; // type name of string
    	book* next;   // type name of string
    book()
    {
    	no=0;
    	author=book=topic=genre=" ";
    	next=NULL; // next given FALSE value
    }
    
    
       
    	void setnext(book *t) 
      {
    	next=t;
      }
        book* getnext()
     {
    	return next;
     }
    };
    
    	class linklist
    	{
    	book *start;
    	book *current;
    	public:
    	linklist()
    	{
    		start=NULL;
    		current=NULL;
    	}
    
    	void insert(book *tmp)
    	{
    		if(start==NULL)
    		{
    			start=tmp;
    		}
    		else
    		{
    			current=start;
    			while(current->getnext()!=NULL)
    			{
    				current=current->getnext();
    			}
    			current->setnext(tmp);
    		}
    	}
    
    
    	bool search_no(int value)
    		{
    			current=start;
    			while(current!=NULL)
    			{
    				if(current->no==value)
    				{
    					cout<<current->author<<endl;
    					cout<<current->book<<endl;
    					cout<<current->topic<<endl;
    					cout<<current->genre<<endl;
    					cout<<"------------------------------------------------------------------------"<<endl;
    					return true;
    				}
    				else
    					current=current->getnext();
    			}
    			return false;
    		}

  5. #5
    Join Date
    May 2012
    Posts
    10

    Re: Search book by its author from 1st record to last

    my database would contain not more than a hundred books. so thats y i want to reduce it. and moreover i dont know how to do it that way. So also for learning purpose

  6. #6
    Join Date
    May 2012
    Posts
    10

    Re: Search book by its author from 1st record to last

    my database would contain not more than a hundred books. so thats y i want to reduce it. and moreover i dont know how to do it that way. So also for learning purpose.

  7. #7
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,205

    Re: Search book by its author from 1st record to last

    Nobody's going to write the code for you. You can store the books in an array or list and just traverse it until you find the book you want. Since users can add books, a list would be a better container. Your text book should have a chapter on them.

    In the long run, my suggestion is better, and since you don't know how to do it your way either, I'm not sure the comment that you don't know how to do it my way is valid.

    You didn't write the code in your first post I take it? Simple array or list traversal is much simpler than anything in the OP.

  8. #8
    Join Date
    Apr 1999
    Posts
    27,444

    Re: Search book by its author from 1st record to last

    Quote Originally Posted by smrizvi1 View Post
    Alright, now this is what i have. what i want to do now is to search a particular BOOK by its author without using the bubble sorting or binary searching method
    1) It would help if you changed from those char arrays to string variables such as std::string.

    Then your C++ code doesn't have ugly C-string handling functions such as strcpy(), strcmp(), etc. Whenever I see that in an obvious beginner program, it raises the question of what material you're using to learn C++.

    2) Nothing in your code is specific to Visual C++. Your question should have been posted in the non-Visual C++ forum.

    3)
    Code:
    #include <algorithm>
    #include <cstring>
    //...
    class BOOK
    {
       //... whatever
    };
    
    struct BookSearcher
    {
        char m_author[20];
        BookSearcher(const char* author) 
        {
            strcpy(m_author, author);
        }
           
        bool operator()(const BOOK& theBook) const
        {
              return strcmp(theBook.author, m_author) == 0;
        }
    };
    
    bool BookSortByAuthor(const BOOK& theBook1, const BOOK& theBook2)     {
          return strcmp(theBook1.author, theBook2.author) < 0;
    }
    
    using namespace std;
    
    int main()
    {
    
        //....sort books by author
        sort(hd, hd + countBOOK, BookSortByAuthor);
    
        // search for book
        BookSearcher searcher("Joe Smith"); // search for this author
        BOOK* foundBook = std::find_if(hd, hd + countBOOK, searcher);
        if (distance(hd, foundBook) < countBOOK )
        {
             // the book was found.  It is pointed to by *foundBook
        }
        else
        {  /* book was not found */ }
    }
    Now, I didn't compile this, but this is how you would do the sort and search without writing any loops, search code, etc. in C++. You use the std::sort() algorithm and find_if() algorithm functions. The sort is reduced to a single line of code and a function, and the find_if() is a single line of code, using a function object.

    As GCDEF mentioned, no one is going to write all the code for you. I showed an example using a radically different, but "real-world" C++ approach. Now your goal is to understand what I posted, as I won't go into explanation. Any good book on C++ will explain it to you. If it's an assignment, you will need to explain it to your teacher, as they will ask you what those functions do and how you used them.

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; May 18th, 2012 at 02:42 PM.

  9. #9
    Join Date
    May 2012
    Posts
    10

    Re: Search book by its author from 1st record to last

    Thank you Mr. Paul
    I also wanted to know that is it possible search a particular string/char, having more than one word, by just a single word?? I mean If i want to search 'Lord of the rings' and i just input 'rings', is there any way that i get all the books that contain the word 'rings'?

  10. #10
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,205

    Re: Search book by its author from 1st record to last

    Quote Originally Posted by smrizvi1 View Post
    Thank you Mr. Paul
    I also wanted to know that is it possible search a particular string/char, having more than one word, by just a single word?? I mean If i want to search 'Lord of the rings' and i just input 'rings', is there any way that i get all the books that contain the word 'rings'?
    look up strstr.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center