Monday, February 6, 2012

C++ telephone directory program?

I have been working at this for a couple hour and cant figure it out. I need to write a program that looks up a persons phone number according to their name or displays that it can find the number in the directory if that name does not exist. Also this program will ask the user if she wants to look up another person after the initial search, but that part works fine. I created a .txt file to pull the data from, and set it in this format:

First name, last name, phone number.

When I input the persons first name and last name, it will only give me the first person on the lists phone number correctly. All the other people on the list will just display the error message, saying that it could not find that person in the directory. Here is my code. Seems like it will not read past the first line in the .txt file. Any help would be appreciated.





#include %26lt;iostream%26gt;

#include %26lt;string%26gt;

#include %26lt;iomanip%26gt;

#include %26lt;fstream%26gt;

#include %26lt;cmath%26gt;

using namespace std;



int main()

{

ifstream inFile1;

string firstName;

string lastName;

string phoneNumber;

string firstNamedoc;

string lastNamedoc;

string phoneNumberdoc;

int playagain;

//getline(cin, phoneNumberdoc);

//ifstream Infile1;



inFile1.open("TelephoneDirectory.txt")鈥?br>
//exit if file cannot be opened

if (!inFile1)

{

cout %26lt;%26lt;"Cannot open input file."%26lt;%26lt;endl;

return 0;

}



//Order of data from file

inFile1 %26gt;%26gt;firstNamedoc %26gt;%26gt; lastNamedoc %26gt;%26gt; phoneNumberdoc;

do

{

//Ask user to enter first and last name.

cout%26lt;%26lt;"Please enter the first and last name to look up, seperated by a space: " %26lt;%26lt;endl;

cin%26gt;%26gt; firstName %26gt;%26gt; lastName;



{

//inFile1 %26gt;%26gt; firstNamedoc %26gt;%26gt; lastNamedoc%26gt;%26gt;phoneNumberdoc;

if( firstName == firstNamedoc %26amp;%26amp; lastName == lastNamedoc)

cout%26lt;%26lt; phoneNumberdoc %26lt;%26lt;endl;

else

cout%26lt;%26lt;"Number was not in directory."%26lt;%26lt;endl;

}

cout %26lt;%26lt;"Want to continue looking? 0 for no, 1 for yes. " %26lt;%26lt;endl;

cin %26gt;%26gt;playagain;

}

while (playagain == 1);





system("PAUSE");

return 0;



}C++ telephone directory program?
You have to take out the else. Because it is asking this for every single contact and of course if it's not the first one it will tell you it's not in the directory.



You should make a flag and always compare.. if the flag is false when it enters and doesn't change during the check up then the contact doesn't exist and you can say it.



And for what i see too, you're just reading the first contact .



So my recommendation is first make a loop to read and load all the contacts in a structured matrix so you can be more organized about the comparitions :D

No comments:

Post a Comment