You've got the right idea in your code. It seems that you're just getting tripped up over some syntax and a structure.
I wanted multiple functions, one to get the text file of the palindromes, one to see whether or not the list from the text file are palindromes, and a last function as the output displaying the entire list, if they were or weren't a palindrome. |
That's the first problem. Think about it: if you want to process the entire file before printing any of the output, then you'd have to store the whole file within your program, along with whether each line is a palindrome. A better way to handle it is like this:
1 2 3 4
|
while (file is good) {
read a line
process the line
}
|
And to procss a line:
1 2 3 4 5 6
|
print the line
if (line is a palindrome) {
print "is a palindrome\n";
else {
print "is not a palindrome\n"
}
|
To that end, here are my specific suggestions:
1. Get rid of processFile(). Instead, open the file and check whether it's open inside main().
2. Put the read/process loop inside main. There's a handy way to check for errors/end of file:
1 2 3 4
|
string str;
while (getline(fstream, str)) {
processLine(str);
}
|
getline()
returns the stream (fstream in this case). while() is looking for a bool and there just so happens to be a bool conversion built into the stream class that calls the
good()
method.
3: Add processLine(). It looks almost exactly like your printOutput function:
1 2 3 4 5 6 7 8
|
void processLine(string &str)
{
if (isPalindrome(str)) {
cout<<str<< "-- A palindrome.\n";
} else {
cout<<str<< "-- Not a palindome.\n";
}
}
|
4. Add the isPalindrome() function. This takes a string and returns true or false, depending on whether it's a palindrome:
1 2 3 4 5 6 7 8 9 10 11
|
bool isPalindrome(string &str)
{
int len = str.size();
for(int i = 0; i <= len; i++) {
if (str[i] != str[len- i]) {
return false;
}
}
// If you get here then it's a palindrome
return true;
}
|
See if you can put all that together. Once it's working, look at isPalindrome() and see if you can make it faster. (Hint: the code written actually checks each character twice).