Hi everyone,
av been trying to come up witha program that will tell if a string is a plindrome.This wat i did and i can't realise the error;

#include<iostream>
#include<string>
using namespace std;
int main(){
 string s;
 string s2;
 getline(cin,s);
 s2=s;
 string::iterator pos;
 string::iterator pos2;
 bool check;check=true;
 for(pos=s.begin(),pos2=s.end()-1,pos!=s.end(),pos2!=s.begin()-1,pos++;pos2--;){
  if(*pos!=*pos2){
   check=false;
  }
 }
 if(check){
  cout<<"This is a Palindrome\n";
 }else{
  cout<<"This is not a palindrome\n";
 }
 return 0;
}

Hi everyone,
av been trying to come up witha program that will tell if a string is a plindrome.This wat i did and i can't realise the error;
#include<iostream>
#include<string>
using namespace std;
int main(){
string s;
string s2;
getline(cin,s);
s2=s;
string::iterator pos;
string::iterator pos2;
bool check;check=true;
for(pos=s.begin(),pos2=s.end()-1,pos!=s.end(),pos2!=s.begin()-1,pos++;pos2--;){
if(*pos!=*pos2){
check=false;
}
}
if(check){
cout<<"This is a Palindrome\n";
}else{
cout<<"This is not a palindrome\n";
}
return 0;
}

It's called debugging. Which will form a big part of your career later if you get a job in this.

Put lots of couts within the program to find out what's going on, at each stage. Then you should be able to identify the error.

Dont you think there is a prob with your for loop.

The format is for( initial conditions or initialize vars; check condition; after_each_loop) And what you have written is :

for(pos=s.begin(),pos2=s.end()-1,pos!=s.end(),pos2!=s.begin()-1,pos++;pos2--)

You have messed up with the placement of your " ; "

To avoid the complexity of this loop place the init stmts outside the for loop like:

start = s.begin( ) ;
end  = s.end( ) - 1 ;

for( ; start <= end; start++, end-- )

{
   // your stmts here
}

An easier way of doing this is something like:

#include<iostream>
#include<string>

using namespace std;

int main()
{
    string myString = "momimom";
    bool check = true;
    int i=0;
    int size = myString.size();

    for (i=0; i<(size/2)+1; i++)
    {
        if (myString[i] != myString[size-i-1])
            check = false;
    }

    if (check)
        cout << "This is a Palindrome\n";
    else
        cout << "This is not a palindrome\n";

    return 0;
}

Study this and im sure you'll understand it. If not, try using cout << and placing variables that you think you know their values. You'll see that you'll be surprised sometimes... Hope this helps, byeee

This article has been dead for over six months. Start a new discussion instead.