Im having a hard time figuring out what is wrong with my program. I need to write a program that looks up a phone number in a file containing a list of names and phone numbers. The user is to input the first name and last name to look up, and the program should output the phone number or display an output message saying that it is not in the file (phone number directory). Then the program should ask the user if he or she wants to look up another name. Here is what I got the first time I tried to write it:
inFile1.open("TelephoneDirectory.txt");
//exit if file cannot be opened
if (!inFile1)
{
cout <<"Cannot open input file."<<endl;
return 0;
}
//Order of data from file
inFile1 >>firstNamedoc >> lastNamedoc >> phoneNumberdoc;
do
{
//Ask user to enter first and last name.
cout<<"Please enter the first and last name to look up, seperated by a space: " <<endl;
cin>> firstName >> lastName;
{
//inFile1 >> firstNamedoc >> lastNamedoc>>phoneNumberdoc;
if( firstName == firstNamedoc && lastName == lastNamedoc)
cout<< phoneNumberdoc <<endl;
else
cout<<"Number was not in directory."<<endl;
}
cout <<"Want to continue looking? 0 for no, 1 for yes. " <<endl;
cin >>playagain;
}
while (playagain == 1);
system("PAUSE");
return 0;
}
The above program only works if the first name on the file is the one searched, otherwise it displays that the name cannot be found.
I then tried to write it another way, but ths one dosent work either. It gives me an error for the void function. Any help would be greatly appreciated, as I am not completely lost and frustrated at this point.
int main()
{
ifstream inFile1;
string firstName;
string lastName;
string phoneNumber;
string firstNamedoc;
string lastNamedoc;
string phoneNumberdoc;
int playagain;
do
{
//Ask user to enter first and last name.
cout<<"Please enter the first and last name to look up, seperated by a space: " <<endl;
cin>> firstName >> lastName;
phonedir();
cout <<"Want to continue looking? 0 for no, 1 for yes. " <<endl;
cin >>playagain;
}
while (playagain == 1);
}
Void phonedir(string firstName, string lastName)
{
Int flag = 0;
inFile1.open("TelephoneDirectory.txt");
//exit if file cannot be opened
if (!inFile1)
{
cout <<"Cannot open input file."<<endl;
return 0;
}
//Order of data from file
Do
{
inFile1 >>firstNamedoc >> lastNamedoc >> phoneNumberdoc;
Void phonedir(string firstName, string lastName)
{
Int flag = 0;
inFile1.open("TelephoneDirectory.txt");
//exit if file cannot be opened
if (!inFile1)
{
cout <<"Cannot open input file."<<endl;
return 0;
}
void function does not return anything. consider it as a null. if youre returning 0, try using bool
are you trying to put the name inside an array or not? if yes, do a search function that will loop through the array.
so
1 2
if (firstNamedoc == arrayname[index])
return index