I am having some trouble with this program that needs to search an array for a string that the user inputs, and then print the entire line with the matching string. At the moment, this is only partially working as is only prints out the string if there is a match and not the entire line that string is on. Here is the text file with the data.
Murray Jones, 555-1212
Christal Delamater, 555-4587
Zetta Smith, 555-6358
Elia Roy, 555-5841
Delmer Bibb, 555-7444
Smith Nevers, 555-7855
Roselle Gose, 555-3211
Jonathan Basnett, 555-5422
Marcel Earwood, 555-4112
Marina Newton, 555-1212
Magdalen Stephan, 555-3255
Deane Newton, 555-6988
Mariana Smith, 555-7855
Darby Froman, 555-2222
Shonda Kyzer, 555-3333
Jones Netto, 555-1477
Bibone Magnani, 555-4521
Laurena Stiverson, 555-7811
Elouise Muir, 555-9633
Rene Bibb, 555-3255
And here is the code that I have so far. If you could help me out I would appreciate it!
void searchArray(string array[], int size)
{
string userInput;
bool found = false;
cout << "Enter a name to search the data: " << endl;
cin >> userInput;
for (int i = 0; i < size; i++)
{
if (userInput == array[i])
{
found = true;
cout << endl;
cout << "Matching Names: " << endl;
cout << array[i] << endl;
}
}
}
Here is the main() that reads the file and puts each line into an array.
int main()
{
ifstream infile;
infile.open("Data.txt");
int numOfEntries = 0;
string nameAndNumber, line;
string *namesAndNumbers = nullptr;
if (!infile)
{
cout << "Error opening file.";
return 0;
}
else
{
while (getline(infile, line))
{
numOfEntries++;
}
namesAndNumbers = new string[numOfEntries];
infile.clear();
infile.seekg(0, ios::beg);
int i = 0;
while (getline(infile, line))
{
stringstream ss(line);
ss >> nameAndNumber;
namesAndNumbers[i] = nameAndNumber;
i++;
}
}
cout << "The number of entries in the file is: " << numOfEntries << endl << endl;
searchArray(namesAndNumbers, numOfEntries);
delete[] namesAndNumbers;
return 0;
}