The problem:
Palindromes are words or phrases that read the same backwards as forwards. Write a C++ program that indicates whether each line on an input file, called sentences.txt and given on my homepage, contains a palidrome. Those lines of sentences.txt that are palidromes should be written to an output file, called palindromes.txt.
The input file given:
Vanna, wanna V?
Must sell at tallest sum.
I should get an eighty. Why? Because I get an eighty in all my other classes.
Lager, Sir, is regal.
I don't need documentation. The code is obvious to me. OK, but is it to the next programmer?
Evil olive.
I never thought computer science could be such fun!
Sex at noon taxes.
You expect me to read ten chapters in two days? No, I expect you to read ten chapters over the semester.
Never odd or even.
(all sentences are on one line)
My code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
bool isPalindrome(string, int);
int main()
{
string sentence;
bool Palindrome;
int len;
ifstream inData;
ofstream outData;
inData.open("sentences.txt");
outData.open("palindromes.txt");
if (!inData)
{
cout << "Can't open input file successfully";
return 1;
}
if (!outData)
{
cout << "Can't open output file successfully";
return 2;
}
getline(inData, sentence);
while(inData)
{
len = sentence.length();
len--; //Accounting for an array storing a value in a zero position
Palindrome = isPalindrome(sentence, len);
if (Palindrome)
cout << sentence << endl;
getline(inData, sentence);
}
return 0;
}
bool isPalindrome(string sentence, int len)
{
string temp = sentence;
for (int i = 0; i == len; i++)
{
if(isalpha(sentence[i]))
temp[i] = tolower(sentence[i]);
//Stores all characters as lowercase in a temporary string
}
for (int i = 0; i < len; i++)
{
while (ispunct(temp[i]) || isspace(temp[i]))
i++;
while (ispunct(temp[len]) || isspace(temp[len]))
len--;
if (sentence[i] != sentence[len])
return false;
len--;
}
return true;
}
Keep in mind for now I'm just testing with cout rather than the output file until I get it to work.
The issue is that it only prints the first sentence and I'm not entirely sure why. I'm pretty sure it isn't something wrong with obtaining the sentence input because of a test that I did earlier, but suspect that something might be wrong with my function to test whether or not the sentence is a palindrome.
My exact output:
Vanna, wanna V?
Any help would be greatly appreciated, I have a feeling it's just a simple error on my part.