简体   繁体   English

使用指针的C ++反转字符串

[英]C++ Reversal string using pointers

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. 非常感谢您提供任何有关如何解决此问题或对指针知识的一般帮助的信息。

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: 只要改变迭代的限制,停车时headtail在中间相遇,你会没事的:

for(int i=0; i<input.length()/2; i++) {
  ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM