2017-07-07 86 views
0
std::vector<std::string> elems = split(command, ' '); 
const int argc = elems.size(); 
wchar_t** argv = new wchar_t*[argc](); 
//wchar_t* argv[10]; 
for (int i = 0; i < argc; i++) { 
    const char* arg = elems[i].c_str(); 
    int size = strlen(arg); 
    size_t length = 0; 
    wchar_t* e = new wchar_t[size]; 
    mbstowcs_s(&length, e, size + 1, arg, size); 
    argv[i] = e; 
} 

这是我试图将字符串矢量转换为wchar_t **的代码。当我评论第三行并取消注释第四行时,它可以工作。但是我希望我的wchar_t **能够坚持下去,所以我想使用第三行而不是第四行。请向我解释为什么第三行不能按预期工作。从矢量<string>转换为wchar_t **

+0

出了什么问题? – pm100

+0

请描述您的问题。取消注释第三行时会发生什么? –

+0

当我使用调试器遍历代码时,我发现argv [0]被设置为elems [0],但即使我从0前进到argc,argv [1],argv [2]等也不是更新。 –

回答

1

您可以从字符串转换为wstring的是这样的:

std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> cv; 
auto warg = cv.from_bytes(arg); 
auto wargv = warg.c_str(); // wchar_t* 

但你也可以考虑通过代替int和wchar_t的**矢量:

std::vector<std::wstring> args; 
for(auto& elm : elms) 
{ 
    std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> cv; 
    args.push_back(cv.from_bytes(elm)); 
} 
0

这是基本的改装回答found here

基本上你正在寻找的是一个std::vector<wchar_t*>(有史以来使用过的字符指针向量的几次之一),并将它发送到需要wchar_t**的函数。

#include <vector> 
#include <algorithm> 
#include <iostream> 
#include <string> 
#include <sstream> 

class CommandLine 
{ 
    typedef std::vector<wchar_t> CharArray; 
    typedef std::vector<CharArray> ArgumentVector; 
    ArgumentVector argvVec; 
    std::vector<wchar_t *> argv; 
public: 
    CommandLine(const std::string& cmd); 
}; 

void my_command_line(int numArgs, wchar_t** args); 

CommandLine::CommandLine(const std::string& cmd) 
{ 
    std::string arg; 
    std::istringstream iss(cmd); 
    while (iss >> arg) 
    { 
     size_t length = 0; 
     CharArray cArray(arg.size() + 1); 

     mbstowcs_s(&length, cArray.data(), arg.size() + 1, arg.c_str(), arg.size()); 

     argvVec.push_back(CharArray(arg.begin(), arg.end())); 

     // make sure we null-terminate the last string we added. 
     argvVec.back().push_back(0); 

     // add the pointer to this string to the argv vector 
     argv.push_back(argvVec.back().data()); 
    } 

    // call the alternate command-line function 
    my_command_line(argv.size(), argv.data()); 
} 

void my_command_line(int numArgs, wchar_t** args) 
{ 
    for (int i = 0; i < numArgs; ++i) 
     std::wcout << "argument " << i << ": " << args[i] << std::endl; 
} 

int main() 
{ 
    CommandLine test("command1 command2"); 
} 

Live Example

2

你分配new wchar_t[size]但复制size + 1字符进去。这是未定义的行为。