Search code examples
c++stdstring

Picky std::string char array constructor


Okay, I may be stupid, but I can't figure out what type the string constructor wants me to input as the second argument. This is fine:

unsigned char *cStringWannabe = new unsigned char[length];
baseStream.read((char*)cStringWannabe, length);

std::string *str = new std::string(cStringWannabe, cStringWannabe+sizeof(cStringWannabe));

But that overshots the size by one and doesn't make any sense.

I have no idea what to cast sizeof(cStringWannabe) to in order to please the constructor.

EDIT:

Okay, since I'm wrong here on so many levels, time to clarify things.

I want a function that will read a single character from a fstream, interpret that character as a length of the string and then read following (length) characters into a string object.

I'd prefer if function was given a pointer to existing string that it will then modify to contain the new data.


Solution

  • You can't cast it to anything to please the constructor. Using sizeof here is simply wrong, as it gives you the size of the pointer, not the length of the string. If anything, you want:

     std::string *str = new std::string(cStringWannabe, length);
    

    and you almost never want to be allocating strings dynamically like that, so:

     std::string str(cStringWannabe, length);
    

    and it's doubtful you want to read strings like this:

    baseStream.read((char*)cStringWannabe, length);