This assignment is designed to give you more experience with arrays and with reading files. It uses two-dimensional arrays.
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. When a name that is not listed is asked for, the program should say that the name is not listed and continue. So a session with this program might look like this. The parts in black are typed by the computer, and the parts in blue are typed by the user.
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 number for Tommy is 111-4441 What name shall I look up? Richard I am sorry, Richard is not listed. What name shall I look up? quitBreak your program into at least the following functions, and possibly more.
Test your program by creating a test data file.
char names[MAXENTRIES][MAXLENGTH+1];Similarly, you can create an array to hold the numbers, by
char numbers[MAXENTRIES][MAXLENGTH+1];Now names[0] is an array of characters, MAXLENGTH+1 bytes long, as is names[1], etc.
while(infile >> names[k])The "test" infile>>names[k] first reads a word into names[k], and then returns true if a word was found, and false if no word was found (because there was no more data).
Do not try to read an entire line and then to break the line into the name and number. Instead, directly read a name into the names array and a number into the numbers array. Don't worry about the line breaks at all. They will be skipped over automatically.
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.
To ask whether a name is the string "quit", just write
if(strcmp(name, "quit") == 0)
int search(char names[][MAXLENGTH+1], int n)It is critical that the correct physical size be given, or the program will not work.