GigiWithoutHadid
GigiWithoutHadid

Reputation: 369

how getline works in this code

    int function1(string data){
        stringstream ss(data);
        return function2(ss);
    }
    int function2(stringstream& ss){
        string val;
        getline(ss,val,',');
        return stoi(val);
    }

If I change function2 to

    int function2(stringstream ss){...}

It doesn't work. I would like to know why? The compliation error is

use of deleted function 'std::basic_stringstream<_CharT, _Traits, _Alloc>::basic_stringstream(const std::basic_stringstream<_CharT, _Traits, _Alloc>&) [with _CharT = char; _Traits = std::char_traits; _Alloc = std::allocator]'

And another question is I am curious about how getline actually works. Like the code below:

    while(!getline(ss,val,','))
        cout<<val;

how does getline keep track of the position of iterator after one iteration?

Upvotes: 1

Views: 147

Answers (2)

Clare Jang
Clare Jang

Reputation: 337

Since you try to copy the ss stream and copy method is deleted using (Relatively) new C++ syntax, so the error occurs.

You're not allowing to copy stream, so you want to give it to a function, you must use reference.

You can find some information about

Upvotes: 2

David Thomas
David Thomas

Reputation: 798

Defining int function2(stringstream ss) would require the use of the deleted copy constructor on stringstream. stringstream has deleted the copy constructor and copy assignment operator. streamstream does allow moves.

getline() does not track the stream. stringstream's class definition derives from a streambuf which is responsible for this minutiae/details.

Upvotes: 1

Related Questions