我得到的任务是从用户那里接收字符串输入,并反转字符串的顺序并打印出结果。我的代码是这样的:

#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;
}


当我打印它时,实际上什么都没有改变,而且由于我是指针的新手,我似乎无法理解为什么。这是我遇到的特定问题:

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


非常感谢您提供任何有关如何解决此问题或对指针知识的一般帮助的信息。

最佳答案

您的方法很好,但是...

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


您不是尝试在纸上解决这个问题吗?您将每对字母交换两次,使数组恢复其原始顺序。

只需更改迭代的限制,以在headtail在中间相遇时停止,就可以了:

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

10-07 18:57
查看更多