string basic

Hi everyone I am new to c++ so I am having a problem with my string question.
i have to determine if the string is Palindrome.Palindrome is a word, phrase, or sequence that reads the same backward as forward ex level.
my code keeps giving me 0 as output.
i can use only one return statement and no recursion or break.

really appreciate your help. thanks

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
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <string>
using namespace std;

bool is_Palindrome (string s)
{
	bool isPalindrome = false;
	int len = s.length();
	int backLen = len-1;

	if (s.length() > 1)
	{
		int i = 0;
		while(i > len/2)
		{
			if ( s[i] == s[backLen])
			{ 
				isPalindrome = true;
				
				i++;
				backLen--;
			}
			else 
				isPalindrome = false;
		}
	}
	else if (s.length() == 1)
	{
		isPalindrome = true;
	}
	
	return isPalindrome;
}

int main()
{
	string s = "level";
	cout << is_Palindrome(s)<< endl;
	return 0;
}  
Last edited on
On line 11 you use the right bit shift operator >>. You probably want to use >.

On line 16 you are always comparing the first character in the string. Don't you want to use i here?

hi Peter87,
i made the changes you said but i still returns 0.
Its the condition of the while loop that is the problem. You set i = 0, then the while loop is only entered if i > len/2 which it never is.

change it to

while(i < len/2)

I've tested it and your code works with that change.
thank you demonwolf
Topic archived. No new replies allowed.