繁体   English   中英

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

[英]C++ Reversal string using pointers

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

#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++) {
  ...
}

暂无
暂无

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

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