Converting a c-string to a std::string

Any way I could write this function better?

std::string DataBase::dbOut2String(const char* cstr) 
{ 
    std::vector<char> toString; 
    int index(0); 
    while (cstr[index] != '\0') 
        { 
            toString.push_back(cstr[index++]); 
        } 
    std::string copy(toString.data(), toString.size()); 
    return copy; 
}

I couldn't find a thing in stl, so I wrote this.

If you know something I don't know about this, please tell me.

I want to keep my code modern. stderr vs cerr, and many other things. Who wins?

1 answer

  • answered 2018-07-11 04:12 Galik

    A std::string can be constructed directly from a const char*. You should probably protect yourself from a null pointer so you can do something as simple as this:

    std::string DataBase::dbOut2String(const char* cstr) 
    {
        // std::string blows up if you give it a nullptr
        return cstr ? cstr : "";
    }