Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading