coin cheung
coin cheung

Reputation: 1107

Why can std::copy_n not copy continuously between each call

I got to find std::copy_n with a behavior like this:

stringstream ss;
ss.str("abcdefghij");
string str;
str.resize(10);
std::copy_n(istreambuf_iterator<char>(ss), 5, str.begin());
cout << str << endl;
std::copy_n(istreambuf_iterator<char>(ss), 5, str.begin());
cout << str << endl;

It seems that what I got printed is abcde\n efghij".

Is this the correct behavior of iterator related operations ?

Upvotes: 2

Views: 104

Answers (1)

lubgr
lubgr

Reputation: 38315

The shown usage of std::copy_n with the arguments given should result in an output

abcde
efghi

To explain the above,

std::copy_n(istreambuf_iterator<char>(ss), 5, str.begin());

copies 5 characters starting at 'a' to the beginning of str. str is now "abcde" followed by 5 default char instances, i.e., null bytes (which aren't printed as the first null byte is interpreted as the end sentinel of the string). The null bytes stem from str.resize(10). After this call, ss points to the position of 'e' in ss. The next, identical call

std::copy_n(istreambuf_iterator<char>(ss), 5, str.begin());

copies 5 characters starting at 'e' to the beginning of str. str is now "efghi" followed by 5 null bytes.

If instead the output

abcde
abcdefghij

is desired, you can change the second invocation of std::copy_n to

std::copy_n(std::next(istreambuf_iterator<char>(ss)), 5, str.begin() + 5);

which copies 5 characters starting at 'f' to str, starting at str's first null byte.

Upvotes: 1

Related Questions