Suppose that a file has been prepared containing names and telephone numbers. Each line contains a name (without any spaces) followed by a telephone number (without any spaces). For example, the file might be as follows.
Chuckie | 111-2233 |
Angelica | 662-1111 |
Tommy | 111-4441 |
Phil | 221-7654 |
Lil | 221-4567 |
Your program should start by prompting for the name of the file that contains this data. Then it should read the file into two arrays, one that holds the names and the other that holds the telephone numbers. It should then ask for a name, and should print the corresponding telephone number. It should continue asking for names, and showing telephone numbers, until the string quit is typed. So a session with this program might look like this.
What is the name of the telephone number file? phone.txt What name shall I look up? Angelica The number for Angelica is 662-1111 What name shall I look up? Tommy The nuber for Tommy is 111-4441 What name shall I look up? quit
char names[100][16];Similarly, you can create an array to hold the numbers, by
char numbers[100][16];Note that 16 bytes are allowed for each name, to account for the null terminator. names[0] is an array of characters, 16 bytes long, as is names[1], etc.
Be careful to keep track of how many entries in the names table are actually in use. When you search for a name, you do not want to look at part of the names array that has no information in it.
When you look up a name, and find it at index $k$ in the names array, you should find the corresponding number at same index $k$ in the numbers array.
To read the names and phone numbers, just read strings using >>. If you put the read in a test, you can tell whether anything was available to read. You can write, for example,
while(infile >> names[k])
if(strcmp(A,B) == 0)strcmp(A,B) is 0 if strings A and B are the same. To use function strcmp, you need to include header file string.h.