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.
You absolutely can assign const char* to std::string , it will get copied though. The other way around requires a call to std::string::c_str() .
const char* const says that the pointer can point to a constant char and value of int pointed by this pointer cannot be changed. And we cannot change the value of pointer as well it is now constant and it cannot point to another constant char.
This page on string::string
gives two potential constructors that would do what you want:
string ( const char * s, size_t n ); string ( const string& str, size_t pos, size_t n = npos );
Example:
#include<cstdlib> #include<cstring> #include<string> #include<iostream> using namespace std; int main(){ char* p= (char*)calloc(30, sizeof(char)); strcpy(p, "Hello world"); string s(p, 15); cout << s.size() << ":[" << s << "]" << endl; string t(p, 0, 15); cout << t.size() << ":[" << t << "]" << endl; free(p); return 0; }
Output:
15:[Hello world] 11:[Hello world]
The first form considers p
to 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 with cout << ...
. 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 the n
you specify. I think this is the simplest solution, in terms of what you have to write.
std::string str(c_str, strnlen(c_str, max_length));
At Christian Rau's request:
strnlen
is specified in POSIX.1-2008 and available in GNU's glibc and the Microsoft run-time library. It is not yet found in some other systems; you may fall back to Gnulib's substitute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With