0

I have been given the task to receive a string input from the user and reverse the order of the string and print the result out. My code is this:

#include <iostream>
#include <cstring>
#include <string>
using namespace std;

int main() {
    string input;
    char *head = new char, *tail = new char;
    char temp;
    //Get the string from the user that will be reversed
    cout << "Enter in a string that you want reversed: ";
    getline(cin, input);
    //Create and copy the string into a character array
    char arr[input.length()];
    strcpy(arr, input.c_str());
    //Set the points of head/tail to the front/back of array, respectably
    head = &arr[0]; tail = &arr[input.length()-1];
    //Actual reversal part of the code (Does not work)
    for(int i=0; i<input.length(); i++) {
        temp = *(tail);
        *tail = *head;
        *head = temp;
        tail --; head ++;
    }
    //Print the character array
    for(int i=0; i<input.length(); i++) {
        cout << arr[i];
    }
    //Free up memory
    delete head; delete tail;
    head = NULL; tail = NULL;
    return 0;
}

When I print it, literally nothing has been changed and I can't seem to understand why as I'm brand new to pointers. This is the specific block that I'm having trouble with:

    for(int i=0; i<input.length(); i++) {
        temp = *(tail);
        *tail = *head;
        *head = temp;
        tail --; head ++;
    }

Any input on how to fix this or pointer knowledge in general that'd help is greatly appreciated.

1 Answer 1

1

Your approach is good but...

for(int i=0; i<input.length(); i++) {
        temp = *(tail);
        *tail = *head;
        *head = temp;
        tail --; head ++;
    }

Didn't you try working this out on paper? You swap each pair of letters twice, bringing the array back to its original order.

Just change the limit of iteration, to stop when head and tail meet in the middle, and you'll be all right:

for(int i=0; i<input.length()/2; i++) {
  ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

I see exactly what you mean and realize my mistake now, by letting it be just the length, I'll end up right back to where i began. Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.