[英]How to pass string iterator variable to a function in c++?
以下代碼僅使用另一個名為 recurse 的函數打印從 main 函數獲得的字符串。 我只是想知道如何將字符串迭代器變量傳遞給另一個函數。 但是我寫的代碼沒有打印任何結果。 有人可以告訴我錯誤是什么以及我可以做些什么來使代碼正常工作?
#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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.