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.
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)
returntrue;
elsereturnfalse;
}
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?
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.
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;}