Aaron7
Aaron7

Reputation: 277

Char array to string and copy character \0

How can I convert a char field to a string if I have the '\ 0' character stored in some position. For example, if I have "ab \ 0bb", the a.lenght () command will show me that I have only two characters stored

string getString(char *str, int len)
{
    str[len] = '\0';
    string strBuffer = string(str);
    cout << strBuffer.length() << endl;
    return strBuffer;
}

Upvotes: 0

Views: 2385

Answers (1)

user17732522
user17732522

Reputation: 76784

As mentioned in the comments, std::string (which I will assume string and the question is referring to) has a constructor taking the length and allowing null characters:

string getString(char *str, int len)
{
    return {str, len};
}

or if you want to be explicit (to avoid confusion with an initializer list constructor)

string getString(char *str, int len)
{
    return string(str, len);
}

The str parameter should probably also have type const char*, not char*, and the type of len should probably be std::size_t. And probably string should be qualified as std::string as well instead of using using namespace std; or using std::string; (depends on context).

Upvotes: 6

Related Questions