why this is always returning true ?

hi
my problem is that i want to return true when the string are same when they are written in backwards
like noon=noon or radar=radar.
if they arent same then return false....but my code is always returning false.
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
bool isPal(string);


int main()
{
	string A;
	cout<<"please enter the string that you want to check :"<<endl;
	cin>>A;
	isPal(A);
	if(isPal(A)==true)
		cout<<"the string parameter is palindrome"<<endl;
	else cout<<"the string parameter is not palindrome"<<endl;
	getch();

	return 0;
}
bool isPal(string A)
{
	string b;
	int i ;
	int length=A.length();
	for(i=length;i>length;i--)
	{
		b[i]=A[i];
	
	}
	cout<<b;
	if (b==A)
		return true;
	else return false;
}
for(i=length;i>length;i--)

You start with i=length. So how can i ever be greater than length? The condition is always false.

b[i]=A[i];

That makes no sense. What are you trying to accomplish with this line?
Last edited on
why this is always returning true ?
..but my code is always returning false.


Which?
ohh sorry ATHAR
i was just testing that
my originnal code is like this

1
2
3
4
5
6
7
for(i=0;i<length;i++)
	{
		b[i]=A[i];
	
	}
	cout<<b;
	if (b==A)
MOSCHOPS my funtion
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

bool isPal(string A)
{
	string b;
	int i ;
	int length=A.length();
	for(i=length;i>length;i--)
	{
		b[i]=A[i];
	
	}
	cout<<b;
	if (b==A)
		return true;
	else return false;
}
b is a string of length zero, so all of these are out-of-bounds accesses.
If you want to copy A into b, you should do it like this:
1
2
3
4
string b=A;
if (b==A)
	return true;
else return false;


The awkward construct is unnecessary, so that leaves us with:
1
2
string b=A;
return b==A;


Since they're obviously always equal, you can simplify it to:
1
2
3
4
bool isPal(string A)
{
  return true;
}
i dont want it to b always equal wht i want is that i want to save string A in reverse order in string b then i have to compare it wether they r same or nt.......
The mistake you're making is in the copying of letters from one A to b. All you're doing is making an exact copy. You need to copy the letters starting at the END and then backwards.
moschops like this ??
1
2
3
4
5
6
int j=0;
for(int i=length;i<=0;i--)
{
b[j]=A[i]
j++
}

do you want me to do like this ?
Topic archived. No new replies allowed.