簡體   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