Search code examples
c++cstringstdstring

Is std::string a better idea than char* when you're going to have to pass it as a char*?


In a recent question, I learned that there are situations where you just gotta pass a char* instead of a std::string. I really like string, and for situations where I just need to pass an immutable string, it works fine to use .c_str(). The way I see it, it's a good idea to take advantage of the string class for its ease of manipulation. However, for functions that require an input, I end up doing something like this:

std::string str;
char* cstr = new char[500]; // I figure dynamic allocation is a good idea just
getstr(cstr);               // in case I want the user to input the limit or
str = cstr;                 // something. Not sure if it matters.
delete[] cstr;
printw(str.c_str());

Obviously, this isn't so, uh, straightforward. Now, I'm pretty new to C++ so I can't really see the forest for the trees. In a situation like this, where every input is going to have to get converted to a C string and back to take advantage of string's helpful methods, is it just a better idea to man up and get used to C-style string manipulation? Is this kind of constant back-and-forth conversion too stupid to deal with?


Solution

  • In the example you give, you can generally read a line into a std::string using the std::getline function: http://www.cplusplus.com/reference/string/getline/

    Of course this doesn't do everything that a curses library does. If you need a non-const char* so that some C function can read into it, you can use a vector<char>. You can create a vector<char> from a string, and vice-versa:

    std::string       a("hello, world");
    std::vector<char> b(a.begin(), a.end());
    
    // if we want a string consisting of every byte in the vector
    std::string       c(b.begin(), b.end());
    
    // if we want a string only up to a NUL terminator in the vector
    b.push_back(0);
    std::string       d(&b[0]);
    

    So your example becomes:

    std::vector<char> cstr(500);
    getnstr(&cstr[0], 500);
    printw(&cstr[0]);