Thread: Help with code

  1. #1
    Registered User
    Join Date
    Nov 2012
    Posts
    73

    Help with code

    The following program will read in a character string, copy it to a character array, enqueue and push the characters into a stack, and then dequeue and pop the stack to compare the letters. The point is to determine whether or not the word is a palindrome.

    The code debugs just fine and brings up the command prompt like it should. However, when I enter a word, the command prompt proceeds past the comparison and asks for another word to enter without displaying whether or not the word is a palindrome.

    The code is below, and the class files are at the bottom. Can someone tell me what's wrong?

    Code:
    #include <iostream>#include <string>
    #include "queue.h"
    #include "stack.h"
    using namespace std;
    
    
    int main()
    {
        string z;
        int y = 0;
        char x[20];
        stack a;
        queue b;
    
    
        cout << "Please enter a word below to test whether or not it is a palindrome." << endl;
        cout << "This program will both push the characters into a stack and enqueue the" << endl << "characters, and then pop/dequeue respectively to compare letters." << endl << endl;
        cout << "If you would like to quit  at any time, enter 'Q'." << endl << endl;
        cout <<"Please enter a word to be tested:  ";
        cin >> z;
    
    
        x[0] = NULL;
    
    
        while (x[0] != 'Q')
        {
            y = 0;
    
    
            while (x[y] != NULL)
            {
                x[y] = z[y];
                a.stack::push(x[y]);
                b.queue::enqueue(x[y]);
    
    
                x[y] = NULL;
    
    
                y++;
            }
    
    
            while (!a.isEmpty())
            {
                while (!b.isEmpty())
                {
                    char c, d;
    
    
                    while (y >= 0)
                    {
                        a.pop(c);
                        b.dequeue(d);
    
    
                        if (c != d)
                        {
                            cout << "That word is not a palindrome." << endl << endl;
                            goto exit;
                        }
                        else if (y == 0  && c == d)
                            cout << "That word is a palindrome." << endl << endl;
                        else
                            y--;
    
    
                    }
                }
            }
    
    
    
    
            exit:
            cout << "If you would like to run the function again, enter a word to be tested." << endl;
            cout << "Otherwise, enter 'Q' to quit." << endl << endl;
            cout << "Please enter a command:  ";
            cin >> x;
        }
    
    
        system("pause");
        return 0;
    }
    
    
    stack::stack(void)
    {
        top = NULL;
    }
    
    
    
    
    stack::~stack(void)
    {
    }
    
    
    
    
    queue::queue(void)
    {
        front = NULL;
    }
    
    
    queue::~queue(void)
    {
    }
    
    
    void stack::push(char x)
    {
        Node *temp;
        temp = new Node;    // create a new node to hold the item to be pushed
        temp->item = x;        // store the item 
        temp->next = top;    // link the node into the list
        top = temp;            // adjust the top pointer
    }
    
    
    
    
    void stack::pop(char &x)
    {
        if (!isEmpty())
        {    
            x = top->item;        // send the top item by reference
            Node *temp;        
            temp = top;            // set a temporary pointer to top
            top = top->next;    // move the top pointer to new top position
            delete temp;        // delete the node that was popped
        }
    }
    
    
    void queue::enqueue(char x)
    {
        Node *temp;
        temp = new Node;    // create a new node to hold the item to be pushed
        temp->item = x;        // store the item 
        if (front == NULL)
            front = temp;
        else
            temp->next = back;    // link the node into the list
    
    
            back = temp;            // adjust the back pointer
    }
    
    
    
    
    void queue::dequeue(char &x)
    {
        if (!isEmpty())
        {    
            x = front->item;        // send the front item by reference
            Node *temp;        
            temp = front;            // set a temporary pointer to front
            front = front->next;    // move the front pointer to new front position
            delete temp;        // delete the node that was dequeued
        }
    }
    
    
    bool stack::isEmpty()
    {
        return (top == NULL);
    }
    
    
    bool queue::isEmpty()
    {
        return (front == NULL);
    }
    
    #pragma once
    
    
    class stack
    {    
    private:
        struct Node
        {
            char item;
            Node *next;
        };
    
    
        Node *top;        
    
    
    public:
        // Constructor & Destructor
        stack(void);            
        ~stack(void);        
    
    
        // Member functions
        void push(char x);
        void pop(char &x);
        bool isEmpty();
    };
    
    #pragma once
    class queue
    {
    private:
        struct Node
        {
            char item;
            Node *next;
        };
    
    
        Node *front;
        Node *back;
    
    
    public:
        // Constructor and Destructor
        queue(void);
        ~queue(void);
    
    
        // Member functions
        void enqueue(char x);
        void dequeue(char &x);
        bool isEmpty();
    };

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,662
    Well 5 meaningless 1-letter variables called x,y,z,a,b certainly don't help in reading the code.

    > The code debugs just fine and brings up the command prompt like it should.
    You mean it compiles.

    Debugging is the next step - making the runnable code do what you want (which it presently doesn't do).

    Start by typing in a single letter, step through the code with a debugger and observe what happens.


    > x[0] = NULL;
    This is the wrong semantic message to the reader.
    Whilst NULL, 0 and '\0' have the same numeric value in the source code, the context of their use is rather different.
    NULL - when you're dealing with pointers, and you want to set a pointer to nothing
    0 - when you're referring to integers, say starting a for loop
    '\0' - when you're marking the end of a c-style string (this is called nul).

    > goto exit;
    You should make the loop be the exit condition, then the loop would end automatically without messy goto's all over the place.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    There is no need to use a char array and risk buffer overflow. There is no need to implement your own stack and queues (the standard library already have them). And there is absolutely no need to do a C-style comparison to check if the strings are palindromes. The standard library have all you need for this. Example:

    Code:
    #include <iostream>
    #include <string>
    #include <algorithm>
    #include <iterator>
    #include <cctype>
    
    int main() 
    {
    	// Reverse word
    	//std::string word = "Dracula";
    	std::string word = "Rats live on no evil star";
    	std::string reversed;
    	std::copy(word.rbegin(), word.rend(), std::back_inserter(reversed));
    
    	// Make first letter upper case and last letter lower case
    	reversed.at(0) = static_cast<char>( std::toupper(reversed.at(0)) );
    	*--reversed.end() = static_cast<char>( std::tolower(*--reversed.end()) );
    
    	// Print out words
    	std::cout << word << "\n" << reversed << "\nIs Palindrom: " << (word == reversed) << "\n";
    	return 0;
    }
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  4. #4
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    You don't need to do "(void)" in C++. Just use an empty "()".

    Shouldn't your destructors be cleaning something up?

    Check the FAQ for a better alternative to system("pause");
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  5. #5
    Registered User
    Join Date
    Nov 2012
    Posts
    73
    The functions with (void) in them are functions that I have not written. This is homework, and my teacher has generously given us some classes and implementation code, and that is why those are there.

    I think I have an idea at what's going wrong. I've made some progress, but it's still not displaying. I've already asked her for help, and the goto function I entered seems to have no problems. My question is, since I have to convert from a string to a character array, is the way I'm doing it working?

    Basically, what I'm doing is this:

    Code:
    string string;
    char array[20];
    int placement = 0;
    
    cout << "Please enter a word to be tested:  ";
    cin >> string;
    
    while (string[placement] != NULL) // I entered the \0s in place of the NULLS, but it turned up a syntax error, and the NULLs seem to be working fine.
    {
    array[placement] = string[placement];
    }
    Last edited by Trey Brumley; 05-05-2013 at 06:55 AM.

  6. #6
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Do you need to slavishly follow what your teacher has written? Are you allowed freedom? Your teacher is just teaching you bad things that belong to C.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  7. #7
    Registered User
    Join Date
    Aug 2010
    Location
    Poland
    Posts
    733
    Quote Originally Posted by Elysia View Post
    Do you need to slavishly follow what your teacher has written? Are you allowed freedom? Your teacher is just teaching you bad things that belong to C.
    That's absolutely nothing compared to other teachers. Consider a C++ programmer who:
    - swallows exceptions and returns arbitrary error codes (not even defines, but simple hard-coded constants),
    - claims C# is better because in C++ there are no pointers to member functions (he likes delegates),
    - doesn't know the difference between a pointer and a reference,
    - follows the "less lines, better code" rule.

    That guy is high-ranked and still teaches.

    My favourite is another one, through. It's someone who talked about character encoding standards and had never heard about Unicode before. When I tried to explain UTF-8 in the lecture room, he didn't seem to believe that something like that exists.

    I'm tempted to make a complete list of their failures, but after I graduate - just to be safe.
    Last edited by kmdv; 05-05-2013 at 07:35 AM.

  8. #8
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Oh, there are many worse teachers out there, especially those who teach students to use Turbo C and void main. But the point is - the OP's teacher isn't doing him/her any favours by requiring the OP to use unsafe code when there are much better alternatives.
    I'd rather have someone who barks at how "unsafe" a code is than someone who writes unsafe code daily.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 09-19-2012, 01:58 PM
  2. Replies: 14
    Last Post: 04-01-2008, 02:23 AM
  3. producing c/c++ code from flowcharts,pseudo code , algorithims
    By rohit83.ken in forum C++ Programming
    Replies: 3
    Last Post: 02-20-2008, 07:09 AM
  4. Having trouble translating psudeo-code to real-code.
    By Lithorien in forum C++ Programming
    Replies: 13
    Last Post: 10-05-2004, 07:51 PM
  5. Replies: 0
    Last Post: 02-21-2002, 06:05 PM