[英]Converting from vector<string> to wchar_t**
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 **保持不變,所以我想使用第三行而不是第四行。 請向我解釋為什么第三行不能按預期工作。
您正在分配new wchar_t[size]
但將size + 1
字符復制到其中。 那是未定義的行為。
您可以像這樣從string轉換為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));
}
這基本上是對此處答案的改進。
基本上,您正在尋找的是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");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.