Thread: Palindrome-kinda program with pointers

  1. #1
    Registered User
    Join Date
    Apr 2009
    Location
    ...creepy
    Posts
    75

    Palindrome-kinda program with pointers

    I am writing a program and I need some help. I need to know how to analyze a string, and then word by word reverse the order of that string. For example:

    User Input: Hello to the world!
    Program Output: olleH ot eht !dlrow
    First problem: I need the program to read the string word by word, and sort of isolate each word. How do I do this?!

    Second problem: After isolating each word, I would like to use a pointer variable that assigned to the first character, and then a pointer variable that is assigned to the last character of the SAME word, and then switch those. Continue for all the words in the entire string, like my example above.

    NOTE: I know there are reverse(), begin(), and end() member functions, but I do not want to do that. I want to MANUALLY do this through my program. Thanks for the help!

  2. #2
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Rather than ask "How do I do this?", you should first try to do it on your own - when/if you hit a major snag along the way, feel free to post the code you're working with, and a description of the errors that you encounter. That way, we know that you're making an effort, and you actually learn something. You can start by reading user input, line by line, and printing it to the screen. Detecting individual words can be done by first setting a boolean flag representing "reading a word" (RW) to false, then, follow this simple logic: if we encounter a non-character (or end of string) and RW is true then store the word buffer somewhere, empty it, and set RW to false. Otherwise, if it's a non-space character, append it to the word buffer and set RW to true. To reverse a string, start by using indexes instead of pointers (much less error prone). Begin at LENGTH - 1, but ONLY if SIZE is greater than zero. Good luck.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  3. #3
    Registered User
    Join Date
    Apr 2009
    Location
    ...creepy
    Posts
    75
    sounds good, thanks. OK, well, here I have a part of my main() function, but I cannot determine how to split up my string word by word. I know how to reverse the whole thing, but I really cannot get much farther than that.

    Code:
    string input;
    char *first, *last;
    cout << "Enter the string you want to reverse: ";
    getline(cin, input);
    for (int i = (input.size() - 1); i >= 0; i--)
            cout << input[i];
    *first should address the first character in the word, and *last should address the last character in the word. Thanks for the help in advance!

  4. #4
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    First of all, strings are not arrays of chars, so it doesn't make sense to form char pointers to them (which isn't to say that you can't, it just isn't appropriate in this context). A string::const_iterator (or string::const_reverse_iterator, in this case) is the logical equivalent. For extracting words, take a look at the pseudocode I posted earlier again and see what you can come up with.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  5. #5
    Registered User
    Join Date
    Apr 2009
    Location
    ...creepy
    Posts
    75
    here is a new version of the code: however i am problem with this run-time error, i believe. when i run the program (perfectly compiled and no errors), it basically opens up the program and then closes it immediately. maybe you might know what is wrong with it. thanks for the help. I think i may have captured what you meant in your last post...


    Code:
    string input, word;
      char *front, *rear; 
      vector <string> string; // This will hold the individual words temporarily until they are replaced
     
      cout << "Enter a sentence that you would like to reverse: ";
      getline(cin, input);
     
      // Puts the string into a stream
      istringstream break_apart(input);
     
      while (break_apart >> word)
      {
        *front = word.at(0);
        cout << *front;
        *rear = word.at(word.size() - 1);
        cout << *rear;
        string.push_back(word);
      }
    the error has to come from the pointer references towards the end. but why?!

  6. #6
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Your pointers are uninitialized; eg: they don't point to valid memory addresses.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  7. #7
    Registered User
    Join Date
    Apr 2009
    Location
    ...creepy
    Posts
    75
    Ok, now I'm in another rut. I understand how to search the word and then switch the first and last characters, working inwards. But I do not know how to put the whole word together. If I inputted "Hello", I would expect the program to output "olleH." The way I have it, my program outputs "oH le l." How do I achieve the expected way?!? Here is the main part of my code. Thank you very much for all the help to everyone on this post!!!

    Code:
    istringstream break_apart(input);
     
      while (break_apart >> word)
      {
        
           for (int i = 0; i < (word.size() / 2); i++)
           {
               front = &word.at(i);
               rear = &word.at(word.size() - 1 - i);
               
               char temp = *front;
               *front = *rear;
               *rear = temp;
               cout << *front << " " << *rear << " ~ ";
           }
          
        string.push_back(word);
      }

  8. #8
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    You're probably just getting confused by the print statement in the loop. Remove that line and it works fine.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  9. #9
    Registered User
    Join Date
    Apr 2009
    Location
    ...creepy
    Posts
    75
    I commented out the line, but it still isn't working. maybe i'm not understanding what you're saying...

    Can you tell me how to permanently change a character, so that when I output 'word' after my search/palindromesque loop it outputs "olleH". Like I said I uncommented that print line like you said, and then I outputted 'word' after my loop and it printed "Hello."

    Thanks for the help!

  10. #10
    Registered User
    Join Date
    Oct 2008
    Posts
    1,262
    Why are you using istringstream? cin itself is a stream; you can do the same with that as you're doing with the istringstream.

  11. #11
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    >> Like I said I uncommented that print line like you said, and then I outputted 'word' after my loop and it printed "Hello."

    Why don't you post the entire program so that we can have a look at it.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  12. #12
    Registered User
    Join Date
    Apr 2009
    Location
    ...creepy
    Posts
    75
    Something like this. I realize that my first for loop will not capture all of the characters. It misses the middle one. But run this, and you'll see what I mean that I cannot get the "olleH" way. Thank you very much!



    Code:
    #include <iostream>
    #include <sstream>
    #include <string>
    #include <vector>  
    void swap (char *front, char *rear); 
    using namespace std;
     
    int main()
    {
      string input, word;
      char *front, *rear; 
      vector <string> string; // This will hold the individual words temporarily until they are replaced
     
      cout << "Enter a sentence that you would like to reverse: ";
      getline(cin, input);
     
      // put the sentence into a stream
      istringstream break_apart(input);
     
      while (break_apart >> word)
      {
         if (word.size() % 2)
        {
           for (int i = 0; i < (word.size() / 2); i++)
             {
                 front = &word.at(i);
                 rear = &word.at(word.size() - 1 - i);
                 
                 swap(*front, *rear);
                 cout << *front << " " << *rear << " - ";
             }
        }
        else 
             for (int i = 0; i < (word.size() / 2); i++)
             {
                 front = &word.at(i);
                 rear = &word.at(word.size() - 1 - i);
               
                 swap(*front, *rear);
                 cout << *front << " " << *rear << " - ";
             }
        string.push_back(word); 
      }  
    
      return 0;
    }
    void swap (char *front, char *rear)
    {
         char temp = *front;
         *front = *rear;
         *rear = temp;
    }

  13. #13
    Registered User
    Join Date
    Apr 2009
    Location
    ...creepy
    Posts
    75
    OK, so I figured out my problem to the last part. Thank you Sebastiani for the help! However, how do I store my modified string into a dynamic array for future use so that I can output it later on in the program?

    Also, if I wanted to, instead of switching all of the letters around in each word, switch all of the words in string (using the same kinda method), how would I go about doing this?

  14. #14
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Code:
         if (word.size() % 2)
        {
           for (int i = 0; i < (word.size() / 2); i++)
             {
                 front = &word.at(i);
                 rear = &word.at(word.size() - 1 - i);
                 
                 swap(*front, *rear);
                 cout << *front << " " << *rear << " - ";
             }
        }
        else 
             for (int i = 0; i < (word.size() / 2); i++)
             {
                 front = &word.at(i);
                 rear = &word.at(word.size() - 1 - i);
               
                 swap(*front, *rear);
                 cout << *front << " " << *rear << " - ";
             }
    I don't understand quite why you have the same code in both branches.

    A rather simple approach to reversal would be to point one pointer to the beginning and the other to end of the string, and keep incrementing one, decrementing the other and swapping while the pointers point to the same thing or cross each other (while first is less than last).

    Also, if I wanted to, instead of switching all of the letters around in each word, switch all of the words in string (using the same kinda method), how would I go about doing this?
    If you store the words in a vector, you could reverse the vector similarly. Or you could prepend each word to an output string (and add a space).
    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).

  15. #15
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by porsche911nfs
    Also, if I wanted to, instead of switching all of the letters around in each word, switch all of the words in string (using the same kinda method), how would I go about doing this?
    You would have to re-implement the algorithm to work on a std::vector instead of a std::string.

    Actually, if you are willing to learn some template programming, you can implement your own generic reverse algorithm, then apply it twice.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Conversion of pointers to functions
    By hzmonte in forum C Programming
    Replies: 0
    Last Post: 01-20-2009, 01:56 AM
  2. Replies: 5
    Last Post: 05-25-2004, 04:36 PM
  3. Pointers program
    By Jamina in forum C++ Programming
    Replies: 3
    Last Post: 08-06-2003, 02:31 PM
  4. Replies: 5
    Last Post: 11-19-2002, 09:36 PM