Wait, did you want the program to say the input is invalid each time it encounters a difference between the two files? Or only after it has scanned the entire file and found no matching entries?
And no, the two cout statements should be outside the while loops, the last part of the program should be set up similarly to how you first had it, just with Found being the conditional statement rather than the string comparison.
The idea behind this setup is this, when the program first starts it reads the first entry in the example.dat file, then it reads the first entry in the example2.dat file. It then compares them, if they are equal it says "Found it!" breaks out of both loops and the conditional statement
1 2 3 4 5 6 7 8
|
if (Found)
{
cout<<"This order is valid."<<endl;
}
else
{
cout<<"This order is invalid."<<endl;
}
|
prints out
.
If the two strings are unequal it then loads the second string inside example2.dat and compares it with the first string of example.dat, it continues this processes until it reaches the end of example2.dat. At which point it will attempt to load the second string of example.dat(If it exists, if it does not exist then the loop should end) and start it all over again just using the second string of example.dat.
If the cout statements are placed inside the while loop like that then each time a comparison is made between the two strings, it will output "Invalid or "Valid" depending on if they match. I had thought you only wanted either "Invalid or Valid" to show up once which is why I had placed the if statements outside of the loops.
The full code, with a few unneeded things removed should look like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
while(!file.eof() || Found) // The "Is found true?" check is placed at both while statements to ensure that they both end as soon as a match is found.
{
// From your post I assume the entries in the files are separated by spaces.
getline(file, str, ' '); //Get the first string inside example.dat and store it.
while (!file2.eof() || Found) //This is one way to end our loop early, when a match is found it stops the loop
{
getline(file2, str2, ' '); //Get the first string inside example2.dat and store it
if (str == str2)
{
Found = true; //This is our bool to check if a match was found.
}
str2.clear(); // erase str2 so we can check the next string in example2.dat
}
str.clear(); // erase str so we can check the next string in example.dat
}
if (Found)
{
cout<<"This order is valid."<<endl;
}
else
{
cout<<"This order is invalid."<<endl;
}
|
EDIT: Oh, also are you using newline characters in your Example2.dat? You may want to make sure that is consists of nothing but spaces and your data, otherwise getline will pick up those newlines and cause incorrect results.