vendredi 1 mars 2019

if statements not working correctly [C++]

I am writing code to check if a sentence is a palindrome. I feel like my logic is correct, but the if statements for check the reverse of the string do not seem to be working. I have tried many solutions online but still nothing. Every string is seen as not a palindrome. I feel the error is at (sentence == reverse):

#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>

using namespace std;

int main(int argc, char *argv[])  {

while (true) {
  string sentence;
  string reverse = "";

  cout << "Enter a sentence below to check (-1 to end):" << endl;
  getline(cin, sentence);

  if (sentence == "q") {
    break;
  }

  for (int i = sentence.length(); i >= 0; i-- ) {
    reverse += sentence[i];
  }

  cout << sentence << " reversed is: " << "[" << reverse << "]" << endl;

  if (sentence == reverse) {
      cout << sentence << " is a palindrome" << endl;
  } else {
    cout << sentence << " is not a palindrome" << endl;
  }
  cout << endl;
}

}

Any help would be greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire