I have a string to convert, string = "apple" and want to put that into a C string of this style, char *c, that holds {a, p, p, l, e, '\0'}. Which predefined method should I be using?
5 Answers
.c_str() returns a const char*. If you need a mutable version, you will need to produce a copy yourself.
2 Comments
.data() and .c_str() are synonymous, but in C++98 .data() returns a pointer that might not be terminated by a null character \0. "There are no guarantees that a null character terminates the character sequence pointed by the value returned" by .datavector<char> toVector( const std::string& s ) {
vector<char> v(s.size()+1);
std::memcpy( &v.front(), s.c_str(), s.size() + 1 );
return v;
}
vector<char> v = toVector("apple");
// what you were looking for (mutable)
char* c = v.data();
.c_str() works for immutable. The vector will manage the memory for you.
1 Comment
string name;
char *c_string;
getline(cin, name);
c_string = new char[name.length()];
for (int index = 0; index < name.length(); index++){
c_string[index] = name[index];
}
c_string[name.length()] = '\0';//add the null terminator at the end of
// the char array
I know this is not the predefined method but thought it may be useful to someone nevertheless.
1 Comment
You can do it by 2 steps.
convert string -> const char*
const char* -> CString
string st = "my str";
const char* stBuf = st.c_str(); // 1. string to const char *
size_t sz; // save converted string's length + 1
wchar_t output[50] = L""; // return data, result is CString data
mbstowcs_s(&sz, output, 50, stBuf, 50); // converting function
CString cst = output;
Comments
Plain and simple:
size_t copyString2CString(char* cstr, const std::string& str, const size_t maxSize)
{
const char* data = str.c_str();
size_t copySize = str.size();
if (maxSize == 0) return maxSize; // Honestly?
if (!cstr) return 0; // Honestly???
// Mind your termination character
if (copySize + 1 > maxSize) copySize = maxSize - 1;
memcpy(cstr, data, copySize);
cstr[copySize] = '\0'; // Again: Mind your termination character
return copySize;
}
Copies content of str to cstr taking care of the termination character. You should provide the maximum size of cstr via parameter maxSize.
Do not forget to #include <cstring>. Merry copying!
2 Comments
srd:strdup() function is even simpler: char* cstr = std:strdup(str.c_str());. Is not?cstr is pointing to was allocated dynamically. So, give free(cstr) a quick call once you're done. The advantage of my definition above is that there should not be any undefined behaviour (like with strcpy)and that you can control the define the destination memory the source string should be copied to.
std::stringhas:string.c_str()