Brianna Szvenska Brianna Szvenska - 2 months ago 6
C++ Question

Direct converting a const char* text passed trough a function into a vector of chars

Imagine that

MyTextClass
is a custom class that in this case would hold the passed const char
"Hello stackoverflowers"
into a
std::vector<char>
:

class MyTextClass{
private:
std::vector<char> storage;
public:
MyTextClass(const char* _passedchars) //constructor
}


With something like the code above, I want to initialize an instance of
MyTextClass
by passing a text to it:

MyTextClass textholder("Hello stackoverflowers");


Or even the following if I overload the
=
operator within
MyTextClass
:

MyTextClass textholder = "Hello stackoverflowers";


The problem becomes figuring out what the definition of the
MyTextClass
constructor should look like. I say that because while there is no problem in the constructor receiving a
const char
passed directly as text like
"Hello stackoverflowers"
, that is an array an thus its length:

1) can't be devised in advance (because it's a passed text of unknown length);

2) nor figured out within the constructor (because
sizeof(_passedchars)/sizeof(_passedchars[0])
will only assess the the size of the pointer;

3) and also not retrieved with
std::size
or the use of
std::begin
and
std::end
, since there is no implementation of those for
const char
.

And without such informations, I just can't figure it out how to convert the
const char
parameter
_passedchars
of the constructor of
MyTextClass
into the internal
std::vector<char>
that I called
storage
in the code example above.

Therefore, how could I convert the passed
const char
into a
std:vector<char>
within a function, in the case of wanting to create an own char text class?

M.M M.M
Answer

To use this exact constructor declaration you could write (in the class definition in the header):

MyTextClass(const char* _passedchars)
    : storage( _passedchars, _passedchars + strlen(_passedchars) )
{
}

(note: requires #include <string.h> for strlen).

However the string literal is actually an array. By accepting a pointer you lost the length information which was already available. So you could instead have the constructor as:

template<size_t N>
MyTextClass( const char (&passed)[N] )
    : storage( passed, passed + N - 1 )
{
}

In the latter case you could use std::begin(passed), std::end(passed) instead.

Comments