C++ match string in file and get line number
- by Corey
I have a file with the top 1000 baby names. I want to ask the user for a name...search the file...and tell the user what rank that name is for boy names and what rank for girl names. If it isn't in boy names or girl names, it tells the user it's not among the popular names for that gender.
The file is laid out like this:
Rank Boy-Names Girl-Names
1 Jacob Emily
2 Michael Emma
.
.
.
Desired output for input Michael would be:
Michael is 2nd most popular among boy names.
If Michael is not in girl names it should say:
Michael is not among the most popular girl names
Though if it was, it would say:
Micheal is (rank) among girl names
The code I have so far is below.. I can't seem to figure it out. Thanks for any help.
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
using namespace std;
void find_name(string name);
int main(int argc, char **argv)
{
string name;
cout << "Please enter a baby name to search for:\n";
cin >> name;
/*while(!(cin>>name))
{
cout << "Please enter a baby name to search for:\n";
cin >> name;
}*/
find_name(name);
cin.get();
cin.get();
return 0;
}
void find_name(string name)
{
ifstream input;
int line = 0;
string line1 = " ";
int rank;
string boy_name = "";
string girl_name = "";
input.open("/<path>/babynames2004.rtf");
if (!input)
{
cout << "Unable to open file\n";
exit(1);
}
while(input.good())
{
while(getline(input,line1))
{
input >> rank >> boy_name >> girl_name;
if (boy_name == name)
{
cout << name << " is ranked " << rank << " among boy names\n";
}
else
{
cout << name << " is not among the popular boy names\n";
}
if (girl_name == name)
{
cout << name << " is ranked " << rank << " among girl names\n";
}
else
{
cout << name << " is not among the popular girl names\n";
}
}
}
input.close();
}