以下代码只是使用另一个称为递归的函数打印从主函数获得的字符串。我只是想知道如何将字符串迭代器变量传递给另一个函数。但是我编写的代码无法显示任何结果。有人可以告诉我错误是什么以及如何使代码正常工作吗?
#include <iostream>
#include <string>
using namespace std;
void recurse(string::iterator &start, string::iterator &end)
{
while(start != end)
{
cout << *start;
++start;
}
}
int main()
{
string s;
string::iterator i = s.begin(), j = s.end();
cout << "Enter the string here: ";
getline(cin, s);
recurse(i, j);
}
最佳答案
在初始化期间,i and j
指向无效地址(因为s
为空)。但是,当您接受输入时,它将获得一个新字符串,并且i and j
指向旧地址(无效)。
因此,在输入后声明迭代。
string s;
cout << "Enter the string here: ";
getline(cin, s);
string::iterator i = s.begin(), j = s.end();
recurse(i, j);
关于c++ - 如何将字符串迭代器变量传递给C++中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60200739/