带有C ++中的指针和函数的反向字符串

问题描述 投票:0回答:1

[我正在尝试创建一个程序,该程序使用C ++中的指针和函数来反转字符串,但是到目前为止,我的方法仅返回一个空字符串,而不是反转的字符串。

#include <iostream>

using namespace std;

void invertS(string *str_ptr );

int main()
{
   string value {"Hello"};
   string *str_ptr {nullptr};
   str_ptr = &value;
   invertS(str_ptr);
   cout << value;
};

void invertS(string *str_ptr) {
    string str = *str_ptr;
    string temp = "";
    int length = str.length();
    int j = length - 1;
    for (int i = 0; i < length; i++) {
        temp[i] = str[j];
        j--;
    };
    *str_ptr = temp;
};

结果始终只是一个空字符串。请注意,我正在将str_ptr引用的字符串分配给函数内部的新字符串,以便可以在字符串上使用.length。据我所知,由于.length不能用于指针。如果有更好的方法可以做到这一点,我也将不胜感激。

我正在尝试创建一个程序,该程序使用C ++中的指针和函数来反转字符串,但是到目前为止,我的方法仅返回空字符串,而不是反转的字符串。 #include ...

c++ function pointers reference
1个回答
0
投票

您在此处输入新的长度为0的字符串:

string temp = "";
© www.soinside.com 2019 - 2024. All rights reserved.