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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
c_strreturns aconst 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 anstd::stringto a function that expects to work with a C-style string.For example, consider this code:
See it in action.
Notes:
¹ This is not entirely true because an
std::string(unlike a C string) can contain the\0character. If it does, the code that receives the return value ofc_str()will be fooled into thinking that the string is shorter than it really is, since it will interpret\0as the end of the string.