Palindrome Program

Need assitance converting my palindrome program from python to C++

Page 1 of 1

2 Replies - 10106 Views - Last Post: 31 December 2009 - 11:16 PM Rate Topic: -----

#1 Igneus  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 17
  • Joined: 27-December 09

Palindrome Program

Posted 31 December 2009 - 03:45 AM

So I wrote a palindrome program in Python for school. Now I wish to convert it into C++. I have the core code written in C++ because I have taken C++ many years before I learned Python. In my Python version, I was able to use a GUI interface to operate the program. However, my C++ knowledge is quite basic one might say. So I was curious if anyone would be able to help guide me or tell me of some tutorial that might be able to assist me in creating a simple GUI for my palindrome program. I have the Python and C++ code written below. In case anyone was wondering, I took a basic course in C++ about four years ago, and I have just finished a Data Structures course in which we used Python. Most unfortunately I have never really written much in C++ since that class four years ago and the sole purpose of converting this program now is to refresh my mind when it comes to C++.

Below is my Python code

Shane Welsh
Assignment 1
This program is to text a palindrome using queues and containing a simple gui.

from Tkinter import *
import tkMessageBox
import tkFont

class Palindrome(Frame):

	def __init__(self):
		"""Sets up the window and objects."""
		self.master.title("Palindrome Tester!")

		# Label and field for the input string
		font = tkFont.Font(family = "verdana", size = 20)
		font2 = tkFont.Font(family = "times new roman", size = 15)
		self._palindromeLabel = Label(self, text = "Word/Phrase", font = font, fg = "blue")
		self._palindromeLabel.grid(row = 0, column = 0)
		self._palindromeVar = StringVar()
		self._palindromeEntry = Entry(self, justify = "center", font = font2, width = 25, textvariable = self._palindromeVar)
		self._palindromeEntry.grid(row = 1, column = 0)

		# The command buttons
		self._button = Button(self, default = NORMAL, text = "Test", font = font2, width = 15, command = self._test)
		self._button2 = Button(self, text = "Help", font = font2, width = 15, command = self._help)
		self._button3 = Button(self, text = "Quit", font = font2, width = 15, command = self._quit)
		self._button.grid(row = 2, column = 0)
		self._button2.grid(row = 3, column = 0)
		self._button3.grid(row = 4, column = 0)

	def _test(self):
		"""Event handler for the button."""
		self._palindromeEntry.delete(0, END)

	def _help(self):
		"""Produce a help file."""
		text = "Welcome to the palindrome Tester!\n\nA palindrome is a word or phrase that is spelled the same backwards as it is forwards, disregarding punctuation.\nFor this program all you (the user) have to do is enter a word or a phrase into the text box and click the test button!"
		tkMessageBox.showinfo(title = "palindrome Help!", message = text, parent = self)

	def _quit(self):

	def _execution(self):
		"""Computation of the plandrome."""
		string1 = self._palindromeVar.get()
		string1 = string1.replace(' ', '')
		stripped = ""
		f_string = ""
		r_string = ""
		queue1 = []
		queue2 = []
		for punct in string1:
			if punct in "!?,.'-;":
				punct = ''
			stripped = stripped + punct

		string1 = stripped.upper()

		for ch in string1:

		queue2 = queue1[:]

		f_string = "".join(queue1)
		r_string = "".join(queue2)

		if f_string == r_string:
			tkMessageBox.showinfo(title = "Palindrome Tester Results!", message = "Your word or phrase is a Palindrome!!", parent = self)
		elif f_string != r_string:
			tkMessageBox.showinfo(title = "Palindrome Tester Results!", message = "Your word or phrase is not a Palindrome...", parent = self)
def main():
	"""instantiate and execute palindrome."""


Below is my C++ code

#include <stack>
#include <queue>
#include <string>
#include "stdlib.h"
#include <iostream>
using namespace std;

// Modified pop function for queues
template <typename T>
T popq(queue<T> &myqueue)
	T temp = myqueue.front();

	return temp;

// Modified pop function for stacks
template <typename T>
T pops(stack<T> &mystack)
	T temp =;
	return temp;

int main()
	string str = "";
	queue<char> q1;
	stack<char> s1;
	bool flag = true;
	 // Receives the palindrome input from the user
	cout << "Please enter a word or phrase.\n";
	getline(cin, str);

	 // Fills the stack and queue
	for(int i = 0; i < str.length(); i++)

	 // Compares the stack and queue
		if(q1.empty() && s1.empty())
		else if(popq(q1) != pops(s1))
			flag = false;

	 // Determines whether or not the user input was a palindrome
		cout << "\"" << str << "\"" << " is a palandrome!" << endl;
		cout << "\"" << str << "\"" << " is not a palandrome...." << endl;


	return 0;

Well, many thanks in advance for any help that might come my way. :)

P.S. I know the extra pop functions are not really necessary but I like the pop functions to return the value from the top/front.

Is This A Good Question/Topic? 0
  • +

Replies To: Palindrome Program

#2 Bench  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 854
  • View blog
  • Posts: 2,338
  • Joined: 20-August 07

Re: Palindrome Program

Posted 31 December 2009 - 05:45 AM

C++ doesn't have any standard GUI libraries; for those your first step should probably be to choose one of the many 3rd party libraries which are going around (Perhaps a cross-platform library, although there's nothing wrong with the windows API or MFC as such); You might recognise some of their names from Python, e.g. wxWidgets, QT, GTK.

As for standard C++ - there's probably plenty you could learn without touching GUIs.

I can't really see any reason for using a stack/queue for this when your string container is up to the job on its own. Or you could use a std::deque ("Double-Ended QUEue") which is capable of push/pop from both ends.

Also, you don't need to check 'isalpha' before calling tolower - if you perform 'tolower' on a non-alpha char then it will return the same char which you gave it
    std::deque<char> dq;
    for(size_t n(0); n!=str.size(); ++n)
        dq.push_back( std::tolower( ); 

    if(dq.front() != dq.back())
        flag = false; 

if( !dq.empty() ) //just in case pop_front popped the last element

Another advantage of std::string or std::deque is that you can use STL algorithms with them
#include <algorithm> 
    //Mutate with tolower
    std::transform(str.begin(), str.end(),
                   str.begin(), std::tolower); 
transform works like a for-each loop function which mutates every element within a range according to some mutator - in this case the range is from begin to end, and the mutator is tolower. the second begin is showing that the resulting mutation ends up back in str, rather than somewhere else.

there's other 'foreach loop functions' - this one can compare a range of elements for equality.
    bool flag = std::equal(str.begin(), str.end(), str.rbegin()); 
begin and end represent the range of chars in str from first to last, rbegin represents the start of the same range of chars in reverse order ("reversed begin")

This post has been edited by Bench: 31 December 2009 - 06:32 AM

Was This Post Helpful? 0
  • +
  • -

#3 Igneus  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 17
  • Joined: 27-December 09

Re: Palindrome Program

Posted 31 December 2009 - 11:16 PM

Hey thanks for all your help! The only reason I used the stack and queue were because in my Python class the lab instructor required that we used them so that we would become familiar with so I thought I might as well use them in my C++ version of the code. However, in my Python class we did just use the queue for our project and we just reversed the queue for comparison. However, since a stack and a queue pop from different ends it just made sense to me to use both of them to achieve the same results. The program itself may not be the most practical but then again, most programs you write in school aren't in my opinion but then again, they allow you to learn different aspects and different techniques of programming. I am also partially aware that you can learn plenty C++ without GUIs, but for whatever reason I always like GUIs better than the command window :P Again, I thank you for your help and I will definitely check out those cross-platform libraries that you mentioned.

As a side note, I'm really interested in created a 2D top-down RPG game and I have heard that C++, compared to Python, is probably the most practical language to program that in. I know that my experience is probably not high enough to write anything that will work, or at least any time soon that is. However, I also feel that if I can learn to write a game like that, that it will increase my knowledge substantially in the world of programming and not just in C++. One last time, I thank you for you help! :) And happy new years to you!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1