【发布时间】: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