Thread: Reversing a string with RULES!

  1. #1
    Registered User Hexadakota's Avatar
    Join Date
    Jan 2008
    Posts
    21

    Reversing a string with RULES!

    My goal is to take a simple string like "My name is Don Knuth!", print it, then print it in reverse order. The rules are, I need to use this class

    Code:
    class ch_stack{
               public:
                      void reset() {top = EMPTY; }
                      void push(char c) {top++; s[top] = c; }
                      char pop() {return s[top--]; }
                      char top_of() const {return s[top]; }
                      bool empty() const { return (top == EMPTY); }
                      bool full() const { return (top == FULL); }
               private:
                       enum {max_len = 100, EMPTY = -1, FULL = max_len-1 };
                       char s[max_len];
                       int top;
         };
    And the function it comes out of can't actually print anything...it has to be a void function. So I have to send a string (let's call it s1) to this function, the function reverses the string into a new string (let's call it s2) and then int main simply prints s2 and there we should have it.

    This is what I have

    Code:
    #include<iostream>
    using namespace std;
    
    //Function to modify a string and return its value in reverse order
    void reverse(const char s1[], char s2[])
    {
         class ch_stack{
               public:
                      void reset() {top = EMPTY; }
                      void push(char c) {top++; s[top] = c; }
                      char pop() {return s[top--]; }
                      char top_of() const {return s[top]; }
                      bool empty() const { return (top == EMPTY); }
                      bool full() const { return (top == FULL); }
               private:
                       enum {max_len = 100, EMPTY = -1, FULL = max_len-1 };
                       char s[max_len];
                       int top;
         };
         
         ch_stack stack;
         int i = 0;    
         while (s1[i] && !stack.full())
              stack.push(s1[i++]);
         while (!stack.empty())
              s2[i] = stack.pop();
    }
    
    int main()
    {
        void reverse(const char s1[], char s2[]);
        
        char s1[30] =  { "My name is Don Knuth!" };
        char s2[30];                      //String to contain reverse values
        
        cout << s1 << endl;               //Show string's original value
        reverse(s1, s2);
        cout << s2 << endl;               //Show string's final value
        
        system("pause");
    }
    The two things I don't understand are how exactly to make a while loop, implementing that class, to reverse the string, and to have it all in a void function. How does int main know what s2 is if it's not part of its file scope? Does it have something to do with static or something like it? Any help would be great. I am a beginner, so please treat me like one.

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    >> The two things I don't understand are how exactly to make a while loop, implementing that class, to reverse the string
    Doesn't the posted code already do that?

    >> How does int main know what s2 is if it's not part of its file scope?
    What do you mean by this? There are two s2 variables in this code. One is declared in main and the other is declared as a parameter of the reverse function. Each function is using the one it declared. The data ends up being the same for both because when the reverse function is called, the s2 from main is passed to reverse so the s2 in reverse refers to the same array.

  3. #3
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    The class you're given models a stack. Do you have a Scrabble game at home? Here's a little game that should lead you to the solution to your problem.

    First, you write something with the Scrabble stones.

    Then, you take the first stone from the front and write down the letter on it on a sheet of paper. Place the stone aside.
    Take the next stone, write the letter next to the first, and place the stone on top of the first stone.
    Do the same thing with the next, until the word you had spelled out is gone, all the blocks form a large stack, and the original word is on the paper.

    OK, now take the top stone off the stack and write the letter on the paper, on a new line. Discard the stone.
    Take the next stone and write the letter on the paper, next to the first.
    Then the next stone, and the next, until the stack is gone.

    Look at what you've written.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  4. #4
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    >> The two things I don't understand are how exactly to make a while loop, implementing that class, to reverse the string, and to have it all in a void function.

    I take it that, since you wrote this, you know what each of the loops is doing and the significance of their particular conditions.

    Are you looking for improvement suggestions to your stack class?

    >> int main know what s2 is if it's not part of its file scope? Does it have something to do with static or something like it?

    No, review the array data type in your text. Remember that they are passed to functions as a pointer to their first element. (Despite the fact that you can still use arrays like arrays in other functions, it's a different data type.) Pointers, chiefly, manipulate the stuff at the address they contain as a value, (in other words, "point to") like any other data type would, except the data pointed to is manipulated indirectly. And it's really only indirect in the sense that you can assign a pointer to a new address, or NULL as well.

    But as daved said, even a function's parameters are destroyed when the function ends. It's the indirectness of data manipulation that causes them to store the backward result.

    HTH.
    Last edited by whiteflags; 02-20-2008 at 05:58 PM.

  5. #5
    Registered User Hexadakota's Avatar
    Join Date
    Jan 2008
    Posts
    21
    Sweet, thanks for the advice. I'm making progress. This is what I have now.

    The int main() function is the same...the reverse function has been changed to

    Code:
    void reverse(const char s1[], char s2[])
    {
         class ch_stack{
               public:
                      void reset() {top = EMPTY; }
                      void push(char c) {top++; s[top] = c; }
                      char pop() {return s[top--]; }
                      char top_of() const {return s[top]; }
                      bool empty() const { return (top == EMPTY); }
                      bool full() const { return (top == FULL); }
               private:
                       enum {max_len = 100, EMPTY = -1, FULL = max_len-1 };
                       char s[max_len];
                       int top;
         };
         
         ch_stack stack;
         int i = 0;
         stack.reset();    
         while (s1[i] && !stack.full())
              stack.push(s1[i++]);
         int w = 0;
         while (!stack.empty())
              s2[w++] = stack.pop();
    }
    It successfully reverse the string, but now the out put is...

    "My name is Luis Camacho III!
    !III ohcamaC siuL si eman yMπ┬┬wMy name is Luis Camacho III!
    Press any key to continue . . ."

    So it's succesfully reversing the string and returning it, but I'm getting garbage and the original string is still there...Any advice?

  6. #6
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Don't forget to add the null terminator to the second string. A C style string must have a null character to indicate the end of the characters in the string.

    Another option is to initialize s2 to be all null characters (initialize it to 0) so that wherever the reversal stops the rest of the characters will be null already.

  7. #7
    The larch
    Join Date
    May 2006
    Posts
    3,573
    You are failing to null-terminate the output string.

    You might also move the class definition out of the function.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  8. #8
    Registered User Hexadakota's Avatar
    Join Date
    Jan 2008
    Posts
    21
    This may sound stupid, but how exactly to I insert the null terminator into the second string? I'm drawing a blank. I know what it is and how it works, but I don't know the syntax for hard coding it in there.

  9. #9
    The larch
    Join Date
    May 2006
    Posts
    3,573
    For example by doing this:
    Code:
    s2[w] = '\0';
    after the loop where w refers to the next character not in the string.

    Edit: That is all the null-terminator is about. But when you output the string, the output routine determines that this is where the string ends.
    Last edited by anon; 02-22-2008 at 12:24 PM.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. String Class
    By BKurosawa in forum C++ Programming
    Replies: 117
    Last Post: 08-09-2007, 01:02 AM
  2. Compile Error that i dont understand
    By bobthebullet990 in forum C++ Programming
    Replies: 5
    Last Post: 05-05-2006, 09:19 AM
  3. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM
  4. problems with overloaded '+' again
    By Brain Cell in forum C++ Programming
    Replies: 9
    Last Post: 04-14-2005, 05:13 PM
  5. Reversing a String
    By ToasterPas in forum C++ Programming
    Replies: 10
    Last Post: 08-14-2001, 12:20 PM