c++cstringc-str

What is the use of the c_str() function?


I understand c_str converts a string, that may or may not be null-terminated, to a null-terminated string.

Is this true? Can you give some examples?


Solution

  • c_str returns a const char* that points to a null-terminated string (i.e., a C-style string). It is useful when you want to pass the "contents"¹ of an std::string to a function that expects to work with a C-style string.

    For example, consider this code:

    std::string string("Hello, World!");
    std::size_t pos1 = string.find_first_of('w');
    
    std::size_t pos2 = static_cast<std::size_t>(std::strchr(string.c_str(), 'w') - string.c_str());
    
    if (pos1 == pos2) {
        std::printf("Both ways give the same result.\n");
    }
    

    See it in action.

    Notes:

    ¹ This is not entirely true because an std::string (unlike a C string) can contain the \0 character. If it does, the code that receives the return value of c_str() will be fooled into thinking that the string is shorter than it really is, since it will interpret \0 as the end of the string.