Write a program that allows the user to input a name. The program should then re
ID: 3626664 • Letter: W
Question
Write a program that allows the user to input a name. The program should then read from the file and 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.
The first 5 names in the txt file:
1 Jacob Emily
2 Michael Emma
3 Joshua Madison
4 Matthew Olivia
5 Ethan Hannah
Explanation / Answer
// Matthew Jones
#include
#include
#include
using namespace std;
int main(){
string name;
string line;
int num_in_file;
string Malename_in_file;
string Femalename_in_file;
bool maleFound = false;
bool femaleFound = false;
int MaleNum;
int FemaleNum;
cout << "Input a Name" << endl;
cin >> name; // retrieve name.
ifstream myfile ("names.txt");
if (myfile.is_open()) // if the file can be opened, open in.
{
while ( myfile.good() ) // while file is good, search.
{
myfile >> num_in_file; // obtain number.
myfile >> Malename_in_file; // obtain male name.
myfile >> Femalename_in_file;
if(name == Malename_in_file) // if value/name is same as requested
{ // its been found for male.
MaleNum = num_in_file; // This is the male's number.
maleFound = true; // change bool.
}
if(name == Femalename_in_file)
{
FemaleNum = num_in_file; // this is the female's number.
femaleFound = true; // change bool.
}
}
myfile.close(); // close up file.
}
else cout << "Unable to open file" << endl;
// Now for the output.
if(maleFound == true)
{
cout << name << " is ranked " << MaleNum << " in popularity among boys." << endl;
}
if(femaleFound == true)
{
cout << name << " is ranked " << FemaleNum << " in popularity among girls." << endl;
}
if(maleFound == false)
{
cout << name << " is not ranked among the top 1000 boys." << endl;
}
if(femaleFound == false)
{
cout << name << " is not ranked among the top 1000 girls." << endl;
}
system("PAUSE"); // to keep the window open after operation.
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.