I need to send a char array to ostream. Say I have the following print function:
Version 1:
void print(ostream &out, const char *str, unsigned len)
{
out << string(str,len);
}
Version 2:
void print(ostream &out, const char *str, unsigned len)
{
out.write(str,len);
}
Both versions above work to a certain extent. Version 1 looks less efficient because it will create an extra string object (causing memory allocation and data copying).
However Version 2 eliminates formatting possibilities. In the following example Version 1 works great (meaning that io manipulator successfully sets width to 10 and applies it to the next output field) :
out << setw(10);
print(out,s,slen);
Is there a way to keep functionality as in V1, but without paying extra for allocation/memcopy?