I need a way to convert multiple strings into the same char array. For example if I have
string str1;
string str2;
char *myArray = new char[str1.size() + str2.size() + 1];
What's the best way to add the string characters into myArray?
You could use another string to combine the two:
auto myArray = str1 + str2;
You can then access the underlying (constant!) char array with the .c_str method or, if you want to modify certain characters, access them with the operator[] on string.
If you need an actual, modifiable char* style array, use std::vector:
std::vector<char> myArray (str1.begin(), str1.end());
myArray.insert(myArray.end(), str2.begin(), str2.end());
myArray.push_back('\0'); // If the array should be zero terminated
You can then access the underlying, modifiable char array with the .data method.
Note that variable length arrays like char myArray[str1.size() + str2.size() + 1] are a compiler extension that only works on certain compilers. They are not standard C++.
strcpy(myarray,(str1+str2).c_str())
or
strncpy(myarray,(str1+str2).c_str(),(str1+str2).length())
strncpy though.use strcpy and strcat:
strcpy(myArray,str1.c_str());
strcat(myArray,str2.c_str());
although , the expression char myArray[str1.size() + str2.size() + 1] will not compile under C++ , since VLAs are forbidden , use dynamic memory allocation:
char* myArray = new char[str1.size() + str2.size() + 1]
char myArray[str1.size() + str2.size() + 1]is not ok, but look forstrcpyandstrcat