Solved

Palindrome string test

Posted on 2006-07-19
17
4,731 Views
Last Modified: 2008-01-09
I am trying to test if a sting is a palindrome

here is my code

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>

using namespace std;

const char MaxLen = 80;

bool IsPalindrome (char word[]);

int main()
{
char word[MaxLen];

ifstream infile ("words.txt");

while (!infile.eof()){
      
      infile.get (word,MaxLen);
      if (IsPalindrome(word) == 1){
            cout << "Yes--" << word << endl;
      }
      else if (IsPalindrome(word) == 0){
            cout << "No---" << word << endl;
      }

      return 0;
}
}

bool IsPalindrome (char word[]){
      char wordTest [MaxLen];

      wordTest [MaxLen] = _strrev (word);

      if (_stricmp(word,wordTest))
            return true;
      else if
            return false;
}

i get an error when I try to compile when it gets to my  if statement in my IsPalindrome function it says it can not convert a char * to a char.

it also does not like my last return statemnet in the same function.  I think partly because i am not sure what that function should return the words true or false or the numbers 1 or 0
0
Comment
Question by:vlahomt
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 3
  • 2
  • +4
17 Comments
 
LVL 30

Expert Comment

by:Axter
ID: 17142785
Hi vlahomt,

Try changing your function to the following:
bool IsPalindrome (char *word);

Cheers!
0
 
LVL 30

Expert Comment

by:Axter
ID: 17142789
vlahomt,
> it also does not like my last return statemnet in the same function.
Your return should be out side of the loop it's in.
0
 
LVL 30

Expert Comment

by:Axter
ID: 17142795
vlahomt,
>      return 0;
> }
> }
Instead of the above, it should be the following:
  }
     return 0;
}
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:vlahomt
ID: 17142837
what part of the function should I change to char *word  i changed the prototype and the definition and that did not work.

the return statment it does not like is the last one in the IsPalindrome function.

but thanks for pointing out the mistaken placement in the main funciton
0
 
LVL 30

Expert Comment

by:Axter
ID: 17142894
>>wordTest [MaxLen] = _strrev (word);

Are you sure you're not getting the error in above line?

That should be the following:
wordTest [MaxLen] = "";
strcpy(wordTest, _strrev (word));
0
 
LVL 30

Expert Comment

by:Axter
ID: 17142901
>>but thanks for pointing out the mistaken placement in the main funciton

You have an extra if word in the last part.
0
 
LVL 30

Accepted Solution

by:
Axter earned 200 total points
ID: 17142935
   if (_stricmp(word,wordTest))
          return true;
     else if
          return false;

Change the above to the following:
    if (_stricmp(word,wordTest))
          return true;
   return false;
0
 

Author Comment

by:vlahomt
ID: 17143003
i made my code match yours

wordTest [MaxLen] = "";
      strcpy(wordTest,_strrev(word));

and now I get this error message on that line

(44) : error C2440: '=' : cannot convert from 'const char [1]' to 'char'
        There is no context in which this conversion is possible
0
 
LVL 8

Expert Comment

by:manish_regmi
ID: 17143777
it is C++ why not use string class.


string word;

bool IsPalindrome (string& word){
          string rev;

         rev = word.reverse();
        if(rev.compare(word) == 0)
            return true;
       return false;  
}

if you dont have reverse in C++

#include <algorithm>

bool IsPalindrome (string& word){
          string rev;

         rev = word;
         reverse(rev.begin(), rev.end())
        if(rev.compare(word) == 0)
            return true;
       return false;  
}

regards
Manish Regmi
0
 
LVL 17

Expert Comment

by:rstaveley
ID: 17143875
Also consider using reverse iterators rbegin and rend with std::string:

    std::string forward("able was i ere i saw elba");
    std::string reverse(forward.rbegin(),forward.rend());
    bool is_palindome = forward == reverse;

Note also that operator== is equivalent to compare.
0
 
LVL 7

Expert Comment

by:nafis_devlpr
ID: 17143917
ok these are your problems

bool IsPalindrome (char word[]){
     char wordTest [MaxLen];

     wordTest [MaxLen] = _strrev (word);<<------------------------problem1

     if (_stricmp(word,wordTest))<<<-----------------------------problem2
          return true;
     else if
          return false;
}

problem 1 is syntax error, because what you are trying to do is assiging a char* to a char value which is an error. problem 2 is logical error, because strcmp returns 0 for a completely matched string otherwise -ve if the first string is lexicographicaly small and +ve(>0) for large. you can change the function in the following way:

bool IsPalindrome (char word[])
{
   if(_stricmp( word, _strrev( _strdup( word ) ) ) == 0)
        return true;
  return false;
}

I am using strdup, because you don't have to know the length of the input string.

Hope this helps

Nafis
0
 
LVL 7

Expert Comment

by:nafis_devlpr
ID: 17143953
there are other ways to test palindromes, take a look at the following code:

bool IsPalindrome (char word[])
{
    int len=strlen(word),i;
      for(i=0; i < (len/2) && word[i] == word[len-1-i]; i++);
      if(i >= len/2)
            return true;
      return false;

}

although you have change the string to a lowercase or uppercase to work it perfectly, but it will run much faster.

nafis
0
 
LVL 17

Expert Comment

by:rstaveley
ID: 17144547
You can even make a one-liner out of a temporary string constructed from the reverse iterators, as illustrated in the function below.

--------8<--------
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
#include <algorithm>

bool is_palindrome(const std::string& str) {
        return std::string(str.rbegin(),str.rend()) == str;
}

int main()
{
      std::ifstream fin("words.txt");
      std::string str;
      while (getline(fin,str)) {
            transform(str.begin(),str.end(),str.begin(),::toupper);
            std::cout << '"' << str << (is_palindrome(str) ? "\" is " : "\" is not ") << "a palindrome\n";
      }
}
--------8<--------
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 17145267
Just in case you need a solution that is not much more complex than your initial code, take that:

bool is_palindrome(const string& str)
{
      for (int l = 0, r = str.length()-1; l < r; ++l, --r)
            if (toupper(str[l]) != toupper(str[r]))
                  return false;
      return true;
}


Regards, Alex
0
 
LVL 4

Expert Comment

by:Lo-Tan
ID: 17178653
bool IsPalindrome (char word[]){
     char wordTest [MaxLen];

     wordTest [MaxLen] = _strrev (word);

     if (_stricmp(word,wordTest))
          return true;
     else if
          return false;
}

instead of char wordTest[MaxLen]; declare it like this:

const char * wordTest = _strrev( word );

Try that

Also, I always use !strcmp( word, wordTest ) ... which returns true when there is a match
0
 
LVL 17

Expert Comment

by:rstaveley
ID: 17180688
Lo-Tan, you'd need to _strdup the string to prevent _strrev from reversing the string in place in the memory allocated to word[]. Having done that you ought also to keep a pointer to the returned string so that you can free it, because _strdup mallocs the memory required for the returned string and not freeing the memory would cause a heap leak.  

The assignment wordTest [MaxLen] = xxx is wrong too, because MaxLen indexes the (MaxLen+1)th character in a MaxLen-sized array (i.e. it overruns the buffer), but the compiler would warn you about that anyhow, because you'd be attempting to assign a char* to a char.

It is always best to sanity-check code snippets by running tests before committing them. I expect you knew all this anyhow :-)

I hope this comment-assassination doesn't put you off from posting!
0
 
LVL 4

Expert Comment

by:Lo-Tan
ID: 17180751
From my stand point, it looks like a class assignment.  With that said, I do believe const char * will alleviate his problem above, and also, the if statement needs to read

if (_stricmp(word,wordTest))
          return true;
     else
          return false;

(notice I removed the lonely word if)

Either use const char * or do a strcpy( wordTest, _strrev(word) ); instead of wordTest [MaxLen] = _strrev (word);

And yes, a copy would be nice so rev doesn't reverse the passed in word.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question