William S.

asked • 03/01/21

How Do I Output the Corresponding Contact Phone Number for an Inputted Contact Name? (C++)

Previously Queried Background Info:



A contact list is a place where you can store a specific contact with other associated information such as a phone number, email address, birthday, etc. Write a program that first takes as input an integer N that represents the number of word pairs in the list to follow. Word pairs consist of a name and a phone number (both strings). That list is followed by a name, and your program should output the phone number associated with that name.


Ex: If the input is:

3 Joe 123-5432 Linda 983-4123 Frank 867-5309
Frank

the output is:

867-5309


Your program must define and call the following function. The return value of GetPhoneNumber is the phone number associated with the specific contact name.


string GetPhoneNumber(vector<string> nameVec, vector<string> phoneNumberVec, string contactName)


Hint: Use two vectors: One for the string names, and the other for the string phone numbers.


My current issue is that the program does not output the phone number but instead outputs nothing.

This assignment has had me stumped for a while now, so any help would be greatly appreciated.


#include <iostream>
#include <vector>
using namespace std;

string GetPhoneNumber(vector<string> nameVec, vector<string> phoneNumberVec, string contactName) {
string theName;
string thePhoneNum;
string theContName;
string correctPhonNum;
int N;
int nElements;
cin >> N;
cin >> theName;
cin >> thePhoneNum;
cin >> theName;
cin >> thePhoneNum;
cin >> theName;
cin >> thePhoneNum;
nameVec.push_back(theName);
phoneNumberVec.push_back(thePhoneNum);
cin >> contactName;
nElements = phoneNumberVec.size();
for (int i = 0; i < nElements; i++) {
if (i == N-1) {
return phoneNumberVec.at(i);
}
}
return "";
}

int main() {
vector<string> nameVec;
vector<string> phoneNumberVec;
string contactName;
string correctPhonNum;
GetPhoneNumber(nameVec, phoneNumberVec, contactName);
cout << correctPhonNum << endl;

return 0;
}


Patrick B.

You are not comparing the name in the vector to the passed target name. If they are equal, compare returns zer0. You then must set the index of the string and BREAK, as you have found the name
Report

03/01/21

1 Expert Answer

By:

Patrick B. answered • 03/01/21

Tutor
4.7 (31)

Math and computer tutor/teacher

William S.

When I ran the program it didn't output a phone number, just the name of the person whose phone number I need to be outputted.
Report

03/01/21

Laura C.

Doesn't work at all!
Report

02/19/22

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.