954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Kindly help me...

how can the searching code be created?
i've made a program named address book. now i wanna make a function that can search an existing contact details from the file through 2 ways
1) search by name
2) search by phone No.
kindly define me the code in C++
thx

kneel
Newbie Poster
10 posts since Jul 2008
Reputation Points: 8
Solved Threads: 0
 

The simplest, but slowest, way is to do a linear search -- start from the beginning of the file, read each record until you get the one you want. For files written in text mode there isn't much more that can be done to speed up the searches.

A more complicated method is to create an index file that contains key field values and the index value into the data file.

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

If you want to find a name and display the telephone number you have to loop through each person in the address book and then use the strcmp function which takes two char pointers as parameters and returns 0 if they match.

It would look something similar to this:

char *nameToFind = "John";

for (int i = 0; i < peopleCount; ++i) {
   if (strcmp(names[i], nameToFind) == 0) {
      std::cout << phoneNo[i];
   }
}


The only problem with this is that if you want to search for part of a name, the code above wont work. So in order for the program to return "John Smith´s" number by just typing the name "John", you need a seperate function that checks to see whether "John Smith" contains the word "John".
For this try looking up the strstr function.

Hope this helps.

William Hemsworth
Posting Virtuoso
1,591 posts since Mar 2008
Reputation Points: 1,429
Solved Threads: 129
 
A more complicated method is to create an index file that contains key field values and the index value into the data file.

Sounds almost like SQL O_O

Alex Edwards
Posting Shark
972 posts since Jun 2008
Reputation Points: 392
Solved Threads: 109
 
Sounds almost like SQL O_O

Its not nearly as complex as SQL or relational databases.

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You