0

Hello all fledgling programmer here,

I am trying to create a program to identify a Palindrome. First, I enter a string and then it is reversed. Then I compare the original string to the reverse of it to determine if it is a palindrome. My problem is that the program does not ignore cases(Neven would not be considered a palindrome). I have two lines of code which are meant to make the entire string lowercase, but I am unsure of how to call those lines in the if statement. I use an if statement print a statement if the string is a palindrome

for (std::string::size_type i=0; i<abc.length(); ++i)
std::tolower(abc[i],lower);

Here is the entire code

#include <iostream>
#include <string>
#include <locale>

int main() {

    std::locale lower;
    std::string abc;
    std::cout << "Enter Text " ;
    getline(std::cin, abc);
    std::cout<<"Your string is "<<abc<<std::endl;
    abc=std::string(abc.rbegin(),abc.rend()); // reverse string
    std::cout<<"Your reverse string is " <<abc<<std::endl;
    for (std::string::size_type i=0; i<abc.length(); ++i)
    std::tolower(abc[i],lower);

    if(abc==std::string(abc.rbegin(),abc.rend())) {

        std::cout << abc << " is a palindrome"<<std::endl;
    }
    else
    {
        std::cout<<abc<<" is not a palindrome"<<std::endl;
    }

    return 0;
}

I have tried to include "std::tolower(abc[i],lower);" inside the if statement but I received an error. I also tried defining it as a variable to pass that through the if statement, but that failed as well. I am unsure of how to progress. Any help is appreciated

Scott Stensland
  • 26,870
  • 12
  • 93
  • 104
  • @AndrewCheong: Only one, and that's because it was incorrect. And please, there is no need to add another answer saying the same thing as existing answers.... and certainly not in the comments section (wrong place)! – Lightness Races in Orbit Feb 28 '16 at 00:43

2 Answers2

2

std::tolower() is not inplace function, it returns the lowercase ch in its return value.

Try this

abc[i] = std::tolower(abc[i],lower);

Output: After this change

Enter Text Sas
Your string is Sas
Your reverse string is saS
sas is a palindrome
Sam Daniel
  • 1,800
  • 12
  • 22
1

std::tolower does not modify the value passed in, it returns the lowercase letter. So your line:

std::tolower(abc[i],lower);

must be changed to:

abc[i] = std::tolower(abc[i],lower);

Live On Coliru

Thomas
  • 4,980
  • 2
  • 15
  • 30