GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 25-Apr-2009, 18:27
disk97 disk97 is offline
New Member
 
Join Date: Mar 2009
Posts: 13
disk97 has a little shameless behaviour in the past

Palindrome code error


I want to create a program determines whether an input string is a palindrome.

I want to get a output result like below if I type a sting "zyaxwvxbyz",

"The sting is not a palindrome: the character in position 2 is 'a', while the character in position 7 is 'b'."

my code is below
could you advise for me what is wrong?

CPP / C++ / C Code:

using namespace std;

bool IsPalindrome(string);

main()
{
	string userInput;
	int i,j,k;

	cout<< "Type in your word or sentence: ";
	cin >>userInput;

	if(IsPalindrome(userInput) == true)
		cout << "\nThe string is a palindrome.";

	else
		{
		cout << "\nThe string is not a palindrome:";
		cout << " the character in position ";
		cout << j <<" is "<< "'"<< userInput[j] << "', while the";
		cout << " character in position ";
		cout <<	k <<" is "<< "'"<< userInput[k] <<"'.";
		}
	return 0;
}

bool IsPalindrome(string userInput)
{
	int i,j=0,k=0,N=userInput.length();

	bool isPal = true;

	for (i=0;i<N;++i)
	{
		if (userInput[i]!= userInput[N-1-i])
		{
			userInput[i]=j;  
			userInput[N-1-i]=k;
			isPal = false;
		}
	}
    return isPal;
}
Last edited by LuciWiz : 25-Apr-2009 at 19:09. Reason: Please insert your C++ code between [cpp] & [/cpp] tags
  #2  
Old 26-Apr-2009, 01:33
WaltP's Avatar
WaltP WaltP is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Midwest US
Posts: 3,335
WaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to all

Re: palindrome code error


CPP / C++ / C Code:
bool IsPalindrome(string userInput)
{
    int i,j=0,k=0,N=userInput.length();
    bool isPal = true;
    for (i=0;i<N;++i)
    {
        if (userInput[i]!= userInput[N-1-i])
        {
            userInput[i]=j;    // why are you replacing the character with a 0?
            userInput[N-1-i]=k;// why are you replacing the character with a 0?
            isPal = false;
        }
    }
    return isPal;
}
__________________

During the election they said Obama could only be elected when pigs fly. Well, we currently have an epidemic of Swine Flu. Coincidence?
  #3  
Old 26-Apr-2009, 02:02
disk97 disk97 is offline
New Member
 
Join Date: Mar 2009
Posts: 13
disk97 has a little shameless behaviour in the past

Re: palindrome code error


because I wanna find the position and mismatch letters.
  #4  
Old 26-Apr-2009, 09:54
zalezog zalezog is offline
Junior Member
 
Join Date: Oct 2007
Posts: 33
zalezog will become famous soon enough

Re: Palindrome code error


Your function
CPP / C++ / C Code:
bool IsPalindrome(string userInput)
returns a boolean value and never tells you the letters which do not make it a pallindrome.

If you want to find out whether the string is a pallindrome or not as well as determine the non matching characters, may be you can do something like this:
CPP / C++ / C Code:
bool IsPalindrome(string userInput,char &left,char &right,
                                                 int &left_pos,int &right_pos)
//pass all the characters by reference
//if the string is not a pallindrome you display all the 'extra' parameters.

While in your function
CPP / C++ / C Code:
{
	int i,N=userInput.length();

	bool isPal = true;

	for (i=0;i<N;++i)
	{
		if (userInput[i]!= userInput[N-1-i])
		{
			left = userInput[i];  
			right = userInput[N-1-i];
			left_pos =i;
			right_pos = N-1-i;
            isPal = false;
		    break; //You now know the string is not a pallindrome,
            //and you were supposed to find out the FIRST
           //  non matching characters.why to continue further?
        }
	}
    return isPal;
}

In the else part
CPP / C++ / C Code:
.
.
.
.
{
		cout << "\nThe string is not a palindrome:";
		cout << " the character in position ";
		cout << left_pos <<" is "<< "'"<< left << "', while the";
		cout << " character in position ";
		cout <<	right_pos <<" is "<< "'"<< right <<"'.";
		}
  #5  
Old 26-Apr-2009, 12:20
TurboPT's Avatar
TurboPT TurboPT is offline
Senior Member
 
Join Date: Feb 2006
Location: Atlanta, GA
Posts: 1,140
TurboPT is a jewel in the roughTurboPT is a jewel in the roughTurboPT is a jewel in the rough

Re: Palindrome code error


It seems that your original intent was to modify the string with zeroes in the IsPalindrome() function [which will not happen, userInput is only a copy in that fuction], and then loop again [once back in main] to find the zeroed entries.

Why loop twice?
Plus, as WaltP indicated, why alter the string? What if the string already contains other zeroes?

Zalezog is right that you don't know the letters, and as an alternative to his suggestions, this is yet another way that it can be done by just getting the index points where the problem occurred. (see all the comments)

CPP / C++ / C Code:
#include <iostream>
#include <string>

using namespace std;

bool IsPalindrome(string, int*, int*); // two additional arguments.

int main()  // explicitly specify return type.
{
	string userInput;
	int j=0,k=0;  // elminate i.

	cout<< "Type in your word or sentence: ";
//	cin >> userInput; // this will only get a word, not a string.
	getline(cin,userInput); // this will get both.

	cout << "\nThe string \"" << userInput << "\" is "; // common to both conditions
	
	if(IsPalindrome(userInput, &j, &k) == true) // now pass j,k for potential assignment
		cout << "a palindrome.";

	else
	{
		// if we get here, then j and k will have the indexes.
		cout << "not a palindrome:" << endl;
		cout << "The character in position ";
		cout << j <<" is "<< "'"<< userInput[j] << "', while the";
		cout << " character in position ";
		cout <<	k <<" is "<< "'"<< userInput[k] <<"'.";
	}

	return 0;
}

bool IsPalindrome(string userInput, int* j, int* k)
{
	int i, N=userInput.length(); // eliminate j,k.
	int oppositeEnd = 0; // new variable.

	bool isPal = true;

	// Add 'isPal to loop's condition. No need to check
	// the rest of the string once a mismatch is found.
	for (i=0;i<N && isPal;++i)
	{
		oppositeEnd = N-1-i; // calculate N-1-i ONCE.
		
		if (userInput[i] != userInput[oppositeEnd])
		{
			*j = i;		// store the left mismatch index.
			*k = oppositeEnd; // store the right mismatch index.
			isPal = false;
		}
	}
    
	return isPal;
}
Here's some sample runs with those modifications:
Code:
Type in your word or sentence: zyaxwvxbyz The string "zyaxwvxbyz" is not a palindrome: The character in position 2 is 'a', while the character in position 7 is 'b'.
Code:
Type in your word or sentence: disk97 The string "disk97" is not a palindrome: The character in position 0 is 'd', while the character in position 5 is '7'.
Code:
Type in your word or sentence: rats live on no evil star The string "rats live on no evil star" is a palindrome.

EDIT:
If you really want to get fancy, it would be nifty to eliminate all the white spaces [or intelligently ignore them] and then you could verify that a phrase such as this:
"A man a plan a canal panama"
...is also a palindrome! But I'll leave that as an "extra curricular" exercise.
__________________
Use the force...read the source!!
WYCIWYG -- what you code is what you get!
  #6  
Old 27-Apr-2009, 16:30
disk97 disk97 is offline
New Member
 
Join Date: Mar 2009
Posts: 13
disk97 has a little shameless behaviour in the past

Re: Palindrome code error


thank you I got it
  #7  
Old 25-May-2009, 22:43
sidwizrockz sidwizrockz is offline
New Member
 
Join Date: May 2009
Posts: 1
sidwizrockz is on a distinguished road

Re: Palindrome code error


YOU CAN USE THIS CODE IF YOU WISH.....

CPP / C++ / C Code:
#include<iostream.h>
#include<conio.h>
#include<string.h>

void main()
{
  clrscr();
   char str[20];  int i,c=0;
  cout<<"enter string";
   gets(str);

    for(i=0;i<strlen(str);i++)
    {
       if(a[i]==a[strlen(str)-i)
        c++;
       else
       cout<<" character at position"<<i+1<<" is" <<a[i]<<" while at position"<<strlen(str)-i+1<<" is "<< a[strlen(str)-i+1];
}

if(c==strlen(str)/2)
 cout<<"its a pallindrome string";

getch();
}
Last edited by admin : 26-May-2009 at 04:15. Reason: Please insert your example C/C++ codes between [CPP] and [/CPP] tags
  #8  
Old 26-May-2009, 00:28
Kimmo Kimmo is offline
Member
 
Join Date: Mar 2007
Location: Finland
Posts: 285
Kimmo is a jewel in the roughKimmo is a jewel in the roughKimmo is a jewel in the rough

Re: Palindrome code error


Quote:
Originally Posted by sidwizrockz
YOU CAN USE THIS CODE IF YOU WISH.....
It is probably not recommended. Your code tries to be a mix of C and C++ while not succeeding in either of them. It looks like you're trying to include some C++ functionality into a C program you wrote years ago... It's not going to work. What you have posted compiles as neither C nor C++.

Here could be a "C++ed" version of what you posted.

CPP / C++ / C Code:
// #include<iostream.h>
// Standard C++ library header files don't have extensions
#include <iostream>
// I'll just remove this, since I think clearing the screen
// in this case is pretty trivial
// Not worth teaching non-standardness to those new to C++
// #include<conio.h>
// #include<string.h>
#include <string>

// void main()
// main() must return an int
int main()
{
    // These identifiers are wrapped inside the std namespace
    // A using declaration is a simple way to make available the
    // names you need unless you want to use fully qualified
    // names at every occasion
    using std::string;
    using std::cout;
    using std::getline;
    //  clrscr();
    //   char str[20];  int i,c=0;
    // A "C++" way could be to use std::string
    string str;
    int i, c = 0;
    
    cout << "enter string" << std::endl;
    //   gets(str);
    // Replace with std::getline()
    getline(std::cin, str);

    // Use string::size() to find size of string
    for (i = 0; i < str.size() ; i++)
    {
        // What's the 'a' here? Hasn't been declared
        // I'm assuming 'a' == 'str'
        // if(a[i]==a[strlen(str)-i)
        if (str[i] == str[str.size() - i - 1])
            c++;
        else
        {
            cout << " character at position " << i + 1 << " is " << str[i]
                 // the + 1 here should be - 1?
                 // << " while   at position " << str.size() - i + 1 << " is "
                 // << str[str.size() - i + 1] << std::endl;
                 << " while   at position " << str.size() - i - 1 << " is "
                 << str[str.size() - i - 1] << std::endl;
        }
    }

    // Did you consider what is the value of c when the string is a palindrome?
    // Is it str.size() / 2 or is it really str.size() ?
    // if (c == str.size() / 2)
    if (c == str.size())
        cout << "its a palindrome string";

    // getch();
    
    return 0;
}

It's usually a good idea to compile and test if what you post works. It reduces a whole lot of frustration from those people who might try out your code.
 
 

Recent GIDBlogToyota - 2009 May Promotion by Nihal

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
RedHat Linux memory problem nzmose Computer Software Forum - Linux 1 02-Aug-2008 10:07
Two-Tier data dissemination code installation problem nidhibansal1984 Computer Software Forum - Linux 6 16-Sep-2007 11:13
Major newbie problem cynack MS Visual C++ / MFC Forum 1 08-Apr-2007 12:25
functions seems not to exit from a certain code block jaro C Programming Language 3 22-Mar-2006 00:08
Can enum have same name as class? crystalattice C++ Forum 3 08-Dec-2004 17:43

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 18:44.


vBulletin, Copyright © 2000 - 2009, Jelsoft Enterprises Ltd.