user1508519
user1508519

Reputation:

Interesting std::copy from std::vector to std::string behavior

I was messing around with ostream_iterator and realized that when specifying a delimiter, it outputs one too many. So instead I went with ostringstream so I could modify the string before outputting it. But then I realized I should just use a string directly. The one issue is however, with the following code:

code

#include <iostream>
#include <iterator>
#include <vector>
#include <sstream>

int main()
{
    std::vector<int> v(10);
    std::fill(v.begin(), v.end(), 42);

    std::string s(" ", v.size());
    std::copy(v.begin(), v.end(), s.begin());
    std::cout << s << std::endl;

    return 0;
}

the output is:

output:

**********

However with

std::vector<int> v(10);
std::fill(v.begin(), v.end(), 42);

std::ostream_iterator<int> osi(oss);

std::copy(v.begin(), v.end(), osi);

std::cout << oss.str() << std::endl;

The output is

output

 42424242424242424242

Obviously it's converting the number to its ASCII representation. Does it simply do a char cast, or is it a side-effect of the complicated internals of the STL? Regardless, how would I change it to output numbers instead of asteriks?

Upvotes: 0

Views: 490

Answers (1)

Mark B
Mark B

Reputation: 96233

It's just copying the number 42 from int to whatever character type is used in the underlying representation of your string (probably char), truncating any bits that won't fit (in your case, no truncation needed). In then stores this char type into each element of the string. When the string is printed it simply prints the ASCII (or whatever your architecture's character set is) representation of 42.

If you want to print the number 42 as the string 42 on your terminal, you need to use formatted output to do the display. Your ostream_iterator approach seems to be a reasonable approach here.

Upvotes: 1

Related Questions