簡體   English   中英

如何將字符串迭代器變量傳遞給 C++ 中的函數?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM