What is the correct/best/simplest way to convert a c-style string to a std::string.
The conversion should accept a max_length, and terminate the string at the first \0 char, if this occur before max_length charter.
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.
This page on
string::stringgives two potential constructors that would do what you want:Example:
Output:
The first form considers
pto be a simple array, and so will create (in our case) a string of length 15, which however prints as a 11-character null-terminated string withcout << .... Probably not what you’re looking for.The second form will implicitly convert the
char*to a string, and then keep the maximum between its length and thenyou specify. I think this is the simplest solution, in terms of what you have to write.