I am integrating 2 programs and turning them into one (I know, not ideal). I expect command line args to look something like
bin/programName -optionsProgram1 --optionsProgram2
I have parsed the options out so I now have the separate sets of arguments, shown below.
bin/programName -optionsProgram1
bin/programName --opionsProgram2
This is great, just how I need them to be. The problem is that I did that with arguments being pushed onto vectors and now I need to use pointers to character arrays. Can anyone recommend a way to convert my vectors into char* in a better way? Also, these will have to be returned as char** in the end, please keep that in mind with your answers.
I have tried using strncpy and realized there was a type error. My attempt is shown below
.h excerpt
std::vector<std::string> myVec; //hold the arguments, one at each pos
std::vector<char*> myCharArray; //intended location for result of conversion
.cpp excerpt
size_t vecSize = myVec.size()
size_t charVecSize;
myCharArray.resize(vecSize);
for(size_t i=0; i < vecSize; ++i)
{
csize = myVec.size()+1 //include null
myCharArray[i] = new char[csize]
strncpy(myCharArray[i], myVec[i].c_str(), csize);
myCharArray[i][csize-1] = '\0'
}
Try std::vector<const char*>
populated with pointers from std::string::c_str()
, eg:
std::vector<std::string> myVec;
std::vector<const char*> myCharArray;
// populate myVec as needed ...
...
// add +1 if you need the array to be null-terminated...
myCharArray.reserve(myVec.size()/*+1*/);
for (auto &s : myVec) {
myCharArray.push_back(s.c_str());
}
//myCharArray.push_back(nullptr);
or:
myCharArray.resize(myVec.size()/*+1*/);
for (size_t i = 0; i < myVec.size(); ++i) {
myCharArray[i] = myVec[i].c_str();
}
//myCharArray.back() = nullptr;
or:
#include <algorithm>
myCharArray.resize(myVec.size()/*+1*/);
std::transform(myVec.begin(), myVec.end(), myCharArray.begin(),
[](std::string &s){ return s.c_str(); });
//myCharArray.back() = nullptr;
Then you can use myCharArray.data()
(which is const char **
) as needed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.