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

Recommended Answers

All 4 Replies

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.

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.

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

Sounds almost like SQL O_O

Its not nearly as complex as SQL or relational databases.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.