1

I am writing a program that reads from an input file, with a sentence on each line. For example:

Jack and "Jill"

A man, a plan, a canal -- Panama

Never a foot too far, even.

Euston saw I was not Sue.

We must determine whether or not these sentences are palindromes, and I wrote a do while loop. It seems to be working correctly, except I just need it to read the entire line instead of just the first one. I am getting an output saying, assuming my first line is Jack and "Jill":

Jack is not a palindrome

I then ask if the user wants to keep going, which I would want it to go to the next line, so I say Yes and then get

and is not a palindrome

and I can see here that it reads the next word in the sentence, rather than the next line. I assume this is because it is reading white space to determine the next word to look at.

Essentially, I need my program to read the entire line, ignoring punctuation tricks like the quotation marks around Jill, the -- next to Panama, etc. So I would get

Jack and "Jill" is not a palindrome.

A man, a plan, a canal -- Panama is a palindrome.

etc.

Here is my code:

#include <fstream>

#include <string>

#include <iomanip>

#include <iostream>

using namespace std;

int main() {
  string input;
  ifstream infile;
  string keepgoing;
  infile.open("palindromes.txt");

  do {
    infile >> input;
    if (input == string(input.rbegin(), input.rend())) {
      cout << input << " is a palindrome" << endl;
    } else {
      cout << input << " is not a palindrome" << endl;
    }

    cout << "Do you want to keep going? [Yes or No] ";
    cin >> keepgoing;

  } while (keepgoing == "Yes" || keepgoing == "yes");
}
Community
  • 1
  • 1
  • 3
    use `getline`. `operator>>` for `string` only reads a single word – 463035818_is_not_an_ai Oct 25 '19 at 19:46
  • Fun fact: You don't have to reverse the whole string. Just half of it. – user4581301 Oct 25 '19 at 19:50
  • Ok, so I am using getline(infile, input) now, and it is correctly reading all of the lines in my console window when I debug. However, it is saying that none of these phrases are palindromes, when I know that some of them are. Here is my code: https://imgur.com/a/pZxUuZh and here is my output: https://imgur.com/a/c7FxK48 I assume this must be a problem with my if statement. – Adam Keller Oct 25 '19 at 20:03
  • Doc, note: I dissent! A fast never prevents a fatness … I diet on cod. – Adrian Mole Oct 25 '19 at 20:06
  • 1
    You will also need to strip your input of white space, capital letters and other undesirable characters. – François Andrieux Oct 25 '19 at 20:06
  • Possible duplicate of [How to read a complete line from the user using cin?](https://stackoverflow.com/questions/5455802/how-to-read-a-complete-line-from-the-user-using-cin) – Davis Herring Oct 26 '19 at 16:57

0 Answers0