The text file babynames.txt, contains a list of the 1000 most popular boy and gi
ID: 3558459 • Letter: T
Question
The text file babynames.txt, contains a list of the 1000 most popular boy and girl names for the year 2004. This is a space delimited file of 1000 entries in which the rank is listed first, followed by the corresponding boy name and girl name. The most popular names are listed first and the least popular names are listed last.
For example, the file begins with
1 Jacob Emily
2 Michael Emma
3 Joshua Madison
This indicates that Jacob is the most popular boy name and Emily is the most popular girl name. Michael is the second most popular boy name and Emma is the second most popular girl name. Write a program that allows the user to input a name. The program should search for a matching name among the girls and boys. If a match is found, it should output the rank of the name. The program should also indicate if there is no match.
For example, if the user enters the name Justice , then the program should output:
Justice is ranked 406 in popularity among boys.
Justice is ranked 497 in popularity among girls.
If the user enters the name Walter , then the program should output:
Walter is ranked 366 in popularity among boys.
Walter is not ranked among the top 1000 girl names.
Your program should allow the user to enter names indefinitely but it should also provide an option for the user to quit.
Explanation / Answer
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
#define babynames input
int main()
{
ifstream infile("babynames.txt");
if(!infile)
{
cout <<"Unable to open file .so exiting from program " << endl;
return 0;
}
string boy[1000],girl[1000];
int index = 0;
while(!infile.eof())
{
infile >> boy[index] >> girl[index];
index++;
}
int i;
char response = 'y';
string name;
while(response == 'y' || response == 'Y')
{
cout <<"Enter name to search :";
cin >> name;
cout << endl;
for(i=0; i<index; i++)
{
if(boy[i].compare(name)==0) {
cout <<name<<" is ranked "<<(i+1) <<" in popularity among boys." << endl; break; }
}
if(i==index) cout <<name <<" is not ranked among the top 1000 boy names."<< endl;
for(i=0; i<index; i++)
{
if(girl[i].compare(name)==0) {
cout <<name<<" is ranked "<<(i+1) <<" in popularity among girls." << endl; break; }
}
if(i==index) cout <<name <<" is not ranked among the top 1000 girl names."<< endl;
cout <<"Do you want to continue (Enter y for Yes and N for no) ";
cin >> response;
cout << endl;
}
//system("pause");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.