code giving wrong output after comparing against file

Why will my code only output that the password has no match in the file even when it does match a password in the file? The whole program is way longer than this but this should be the section where the error is.

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
  void read(string morse)
{
	string filedata;
	ifstream filename;
	filename.open("masterFile.txt");
	while (getline(filename, filedata))
	{
		compare(morse, filedata);
	}
	if (compare(morse, filedata))
		cout << "The password matches one in the file so it is valid" << endl;
	else
		cout << "The password has no match in the file so it is not valid" << endl;
	filename.close();
	return;
}
bool compare(string morse, string filedata)
{
	bool comparefilemorse = false;
	if (morse == filedata)
		comparefilemorse = true;
	if (comparefilemorse == true)
		return true;
	else
		return false;
}
bool compare(string morse, string filedata)
{
bool comparefilemorse = false;
if (morse == filedata)
comparefilemorse = true;
if (comparefilemorse == true)
return true;
else
return false;
}


That's pretty ugly. I think it works fine, but why have you not written it as:

1
2
3
4
bool compare(string morse, string filedata)
{
	return (morse == filedata);
}



Anyway, look at your code. Only the LAST word in the password file is used for actually producing output (line 10 in the code you posted - ONLY line 10 affects the output, so ONLY the final comparison makes any difference). This loop:

1
2
3
4
while (getline(filename, filedata))
	{
		compare(morse, filedata);
	}


does a whole lot of comparisons, that you ignore completely. What happens if the match is in the middle of that somewhere?
Last edited on
I get what you're saying about my bool function and I get what you mean about the loop only taking the last comparison. I don't understand how to fix my code so that it doesn't ignore matches in the middle. I tried putting the if else with the couts in the while loop but that's not right either.
1
2
3
4
5
6
7
8
9
10
11
bool foundOne = false;
while (getline(filename, filedata))
{
		if (compare(morse, filedata)) 
              {
                      cout << "The password matches one in the file so it is valid" << endl;
                      foundOne = true;
              }
}

if (!foundOne) { cout << "The password has no match in the file so it is not valid" << endl;}
Thanks for helping me with this question.
Topic archived. No new replies allowed.