Search for a String and Find the Rank

Pages: 123
How about this one
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46


void name_search (string name)
{
	int rank;
	string male, female; 
	ifstream infile;
	bool male_name_found=false,female_name_found=false;

	infile.open ("babynames2004.txt");

	if (infile.fail())
	{
		cout << "The file was corrupt.\n";
	}

	while (!infile.eof())
	{
		infile >> rank >> male >> female;
		

		if(name == male && name != female)
		{
			cout << name << " is ranked " << rank << " in popularity among boys.\n";
			male_name_found=true;
		}
		else if(name != male && name == female)
		{
			cout << name << " is ranked " << rank << " in popularity among girls.\n";
			female_name_found=true;
		}
		else if (name == male && name == female)
		{
			cout << name << " is ranked " << rank << " in popularity among boys.\n";
			cout << name << " is ranked " << rank << " in popularity among girls.\n";
			male_name_found=true;
			female_name_found=true;
		}
		
	}
	if(male_name_found==false)
		cout<<"Name not listed among male names";
	if(female_name_found==false)
		cout<<"Name not listed among female names";
	infile.close();
}
Why should it? You would be saying "if the name didn't match, say it isn't there even though it might be".

There is no way that you can do the entire thing inside the loop, how can you talk (cout) about the list of 1000 names when you are somewhere in the middle. Just use a bool and int and remember it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
int maleRank = -1;
int femaleRank = -1;
bool foundMale = false;
bool foundFemale = false;

if (infile.fail())
{
  cout << "The file was corrupt.\n";
}
  
while (!infile.eof())
{
  infile >> rank >> male >> female;


  if (female == input)
  {
    femaleRank = rank;
    foundFemale = true;
  }
  if (male == input)
  {
    maleRank = rank;
    foundMale = true;
  }
}
infile.close();

if (foundMale)
  cout << input << " ranks at number " << maleRank << endl;
else
  cout << input << " was not foundin male list\n";

if (foundFemale)
  cout << input << " ranks at number " << femaleRank << endl;
else
  cout << input << " was not found in female list\n";
Topic archived. No new replies allowed.
Pages: 123