Problems with a C++ Code

May 22, 2010 at 5:09pm
I am a student and I'm doing a project with C++. Actually my program should tell the user if the word given is a palindrome or not. However, it's always saying "NO PALINDROME". Need help, please! Can't find the error!

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
#include<iostream>
#include<string>

using namespace std;

int main(){
    string n, a, b;
    cin>>n;
    int i, p=n.size(), c=1;    
    for (i=1; i<n.size(); (i=i+1)and(p=p-1)){
        a=(n[i]);
        b=(n[p]);
        if (a==b){
           c=c+1;
        }
        else {
           cout<<"NO PALINDROM"<<endl;
           i=n.size();
        }
    }
    if (c==n.size()){
       cout<<"YES PALINDROM"<<endl;
    }
    int z;
    cin>>z;
}
May 22, 2010 at 5:20pm
First thing I noticed was, on line 8 ask for input but you never tell the user what that input is supposed to be.

next two things I noticed was there was no "return 0" at the end of the function and instead of
1
2
    int z;
    cin>>z;

just use cin.ignore(2) essentially the same thing but instead of wasting a variable it just waits for you to hit a button.
Last edited on May 22, 2010 at 5:21pm
May 22, 2010 at 5:30pm
Well, we were told that we did not have to tell the user what should be the input, but I'm OK with the other two things. Despite those facts it continues telling "NO PALINDROME" at any word.

Any idea? What's wrong in it?
May 22, 2010 at 5:30pm
So I found your error. You initialize i to 1 but arrays start at zero so i is looking at the second letter of your word. then secondly, n.size() returns 1 past the number of characters in your array so setting p=n.size() then b=n[p], b is equal to ' ' (a space). So to fix these errors, set i to 0 and p to n.size()-1.

OOOH and also, look at c..... look at it.... look at it.... mmk, so you set it to one, lets go through a loop
cin: aka
a = a
b = a
c = c + 1 == 2 // Weren't we still on the first letter? yeah, so make sure to initialize c to 0 as well
May 22, 2010 at 5:37pm
Thanks a lot ragn4rok234, now it works. I'm really grateful.

Bye!
Topic archived. No new replies allowed.