Write a palindrome

I need to write a program that:
-makes the user input something then it checks if the user has a palindrome or not
-treats capital and lower case letters the same. For example, "a" and "A" should be the same
-it has to exit the program if the user input contains a "q" or "Q"
-removes all spaces from the user input
-only <string> and <iostream> are allowed to be used
-can only use getline, replace, erase,length and find string functions

So far I've only got:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  #include "stdafx.h"
  #include<iostream>
  #include<string>
 
using namespace std;
 
int main()
{
    string str;
    int length;
    cout << "Enter a word: ";
 
    getline(cin, str);
 
    length = str.length();
 
    for (int i = 0; i < (length / 2); i++)
    {
        if (str[i] != str[(length - 1) - i])
            isPalindrome = false;
    }
 
    if (isPalindrome == true)
        cout << str << " is a palindrome" << endl;
 
    else
        cout << str << " is not a palindrome" << endl;
    
   system("pause")L
   return 0;


Any help would be greatly appreciated.
20:13: error: 'isPalindrome' was not declared in this scope

You need to define a
bool isPalindrome; somewhere in main.
Looking at your logic, it looks like you want to initialize it to true, so it would be:
bool isPalindrome = true;, put it somewhere before your for loop.


-treats capital and lower case letters the same

Simplest solution is to change
if (str[i] != str[(length - 1) - i])
to
if (tolower(str[i]) != tolower(str[(length - 1) - i]))
To compare both characters to a common lowercase.

BUT -- you need to #include <cctype> for this, technically... it might still work if you don't, but it isn't guaranteed to work.
You can also make your own "tolower" function, by comparing ASCII values.
http://asciitable.com

remove all spaces from user input

https://stackoverflow.com/questions/83439/remove-spaces-from-stdstring-in-c
might help.

-it has to exit the program if the user input contains a "q" or "Q"
1
2
if (str == "Q" || str == "q")
    return 0;

Last edited on
After minor changes to make it compile, your code works with "friendly" input (all lower case, no spaces).

To handle the case and spaces, I strongly recommend that you write code to create a second "normalized" string from the input. You copy the input string character by character to the normalized string, except:
- change lower case to upper case
- skip spaces
- set a flag if you see "q" or "Q".

Then use your existing code to see if the normalized string is a palindrome.
Topic archived. No new replies allowed.