c++ - 函数将返回一个字符串,其中包含两个索引之间的部分

标签 c++ arrays string pointers function-pointers

我有一个问题,如何返回 char 数组范围(由用户给定)之间的字符串。 示例:

  Entered string is “My name is john".

起始索引:3 停止索引:6 函数将返回“名称”

我的代码在这里,但我只会得到地址作为输出

#include <iostream>
#include <conio.h>
#include <string>
#include <cstring>
using namespace std;

string *section(char*ary, int index_1, int index_2)
{
    string sec=ary;
    string *str;
    str = &sec;
    *str = sec.substr(index_1, index_2);
    return str;
}


int main()
{
    int starting_index = 0;
    int ending_index = 0;

    char *ptr;
    ptr = new char[200];
    int i = 0;
    char ch = _getche();
    while (ch != 13)
    {

        ptr[i] = ch;
        i++;
        ch = _getche();
    }
    for (int j = 0; j < i; j++)
    {
        cout << ptr[j];
    }
    cout << endl;

    cout << "Enter start index: " << endl;
    cin >> starting_index;
    cout << "Enter end index: " << endl;
    cin >> ending_index;
    cout<<section(ptr, starting_index, ending_index);

   delete[] ptr;
  system("pause");
}

最佳答案

你的主要问题是你返回了一个指针。换句话说,你返回一个字符串对象的地址。这有两个作用。首先,您将返回的地址传递给 cout,而不是指向的字符串。如果您的意图是打印字符串,那么您应该取消对指针的引用。但还有另一个问题。返回的指针无效,因为它指向一个在函数结束时被销毁的本地对象。所以你可能不会取消引用指针。这是没用的。

这两个问题都可以通过从 section 中按值返回字符串而不是地址来解决。

please explain difference between these two prototype. string section( paramerters ) and string *section( paramerters )

函数名左边的部分(section)是函数返回对象的类型。 stringstring* 类型的区别在于后者是指针类型。指针的值是指向对象所在的内存地址。因此,前一个函数原型(prototype)声明了一个返回 string 的函数,而后者声明了一个返回字符串指针的函数。

除了错误之外,还有一些其他提示:该函数毫无意义地摆弄指针。 str 变量是不必要的。您从不使用索引参数。在 main 中,您进行了不必要的动态分配。

关于c++ - 函数将返回一个字符串,其中包含两个索引之间的部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35032691/

相关文章:

c++ - 两个 union 之间的循环转换运算符

c++ - 从兼容类型 int 赋值给 int

c++ - 使用参数专门化宏

c++ - 两行后 fstream 没有从文本文件中读取

c++ - 如何使用 C++ 保存网页? Windows或Linux系统

python - 从 python 3 中的字符串中删除 unicode 表示的最简单方法?

java - java中如何删除String中的重复字符

python - 从表示图像的数组中排除周围零的最快方法?

arrays - 任意长度的两个非重叠子数组的最大和

c++ - 在不区分大小写的字符串 vector 中查找字符串 C++