【问题标题】:Function will return a string which holds the section between the two indexes函数将返回一个字符串,该字符串包含两个索引之间的部分
【发布时间】:2016-05-04 03:05:32
【问题描述】:

我有一个问题,我如何在 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");
}

【问题讨论】:

  • 您返回一个指向局部变量的指针。 不要返回指针,按值返回字符串
  • 另外,你可以写std::string(ary + index_1, index_2 - index_1 + 1)来直接创建string——你不需要section支持函数。
  • 但是,如何从 section 函数中获取字符串。
  • 正如 Joachim 所说的 “按值返回字符串” - string section(char* ary, int index_1, int index_2) { return ,正如我所说的 std::string(ary + index_1, index_2 - index_1 + 1);。添加} 就完成了。

标签: c++ arrays string pointers function-pointers


【解决方案1】:

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

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

请解释这两个原型之间的区别。字符串部分(参数)和字符串*部分(参数)

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

除了这个错误之外几乎没有其他提示:该函数毫无意义地摆弄指针。 str 变量是不必要的。您从不使用索引参数。在main 中你做了不必要的动态分配。

【讨论】:

  • 请解释这两个原型之间的区别。 字符串部分(参数)字符串*部分(参数)
  • @jonny 我用那个问题更新了我的答案。有关详细信息,请参阅stackoverflow.com/questions/388242/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多