-1

My assignments requires me to keep accepting input from the user and output whether or not it is a palindrome until the word DONE is inputed. Also, words like Bob must have an output of true because we must disregard case (upper/lower.)

This is my first time using C++.

#include <iostream>
#include <string>
using namespace std;
int main()
{
string wordInput;
while (wordInput != "DONE")
{ 
    cout << "Please enter a word: ";
    cin >> wordInput;
    int wordLength = wordInput.length();
    int wordHalf = (wordLength / 2);
    bool flag = false;
    for (int i = 0; i <wordHalf; i++)
    {
        if (tolower((wordInput[i]) == tolower(wordInput[wordLength-1-i])))
        {
            flag = true;
        }
        else
        {
            flag = false;
            break;
        }
    }
    if (flag == true)
    {
        cout << "true"<<endl;
    }
    else
    {
        cout << "false"<<endl;
    }
}   
return 0;   
}
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
trap28
  • 97
  • 7
  • 3
    You have two wordInput variables, one that is local to the while loop and one that is local to main. That is probably why it's not working. To clarify, the second line of the loop ```string wordInput``` is causing the outer scope variable to be hidden and unchangeable. – nick Feb 02 '19 at 06:39
  • 1
    Could you please edit the question and add a specific clear question? What is the input now? What is the output? What happens? What should happen? – Sami Kuhmonen Feb 02 '19 at 06:39
  • if a word can be read from beginning to end the same way as from end to beginning it is a palindrome. Words like Noon, Racecar, Bob, nun, etc are palindromes. but my program is printing false for words like Racecar, Noon, and Bob even though they are palindromes except the letters are not the same case (upper/lower.) So, this is why inside my loop I convert every character of the string to lower case. But still, it is printing false for Bob, Racevar, Noon. – trap28 Feb 02 '19 at 06:52

2 Answers2

1

It might have something to do with 'wordInput' being declared twice, once right before the while loop and once within it. It is mixing up what the while loops condition is looking at.

1

Your issue with words not being correctly identified comes from this line:

if(tolower((wordInput[i]) == tolower(wordInput[wordLength-1-i])))

If you look carefully, you set the parentheses incorrectly. Try this instead:

if(tolower(wordInput[i]) == tolower(wordInput[wordLength-1-i]))
nick
  • 449
  • 3
  • 12