从argv [1]转换为char *字符串后出现什么问题?

问题描述 投票:0回答:1

我对C和指针非常陌生。我正在尝试将命令行参数转换为wchar_t *。但是不知何故它没有提供适当的输出。我想念什么?

void fun(){
    std::setlocale(LC_ALL, "en_US.utf8");
    std::wcout.imbue(std::locale("en_US.utf8"));
    char* mbstr = "f:\\mypath1\\mypath2\\mypath3";
    wstring reposPath;
    char *c_ReposPathString = (char*)mbstr;
    size_t c_ReposPathStringSize= 0;
    if(c_ReposPathString)   
    {       
         c_ReposPathStringSize = 2*(strlen(c_ReposPathString)+1);   
    }
    wchar_t *w_ReposPathChar = new wchar_t[c_ReposPathStringSize];  
    if(w_ReposPathChar) 
    {       
       mbstowcs(w_ReposPathChar, c_ReposPathString, c_ReposPathStringSize);
    }
       reposPath = w_ReposPathChar;

    printf("%s",  (char *)reposPath.c_str());
    free(w_ReposPathChar);
}

当我打印w_path的长度时,它显示1。But argv[1]它具有多个字符。

c++ argv wchar-t widestring
1个回答
0
投票

您不能简单地将wchar_t字符串重新转换为char字符串并期望它能正常工作,因为可能[ wchar_t值的高字节为零(在投射之后将被视为终结器)。

所以,而不是:

printf("%s", (char *)reposPath.c_str());

[在f后面看到一个'假'nul终止符,只需打印wchar_t字符串就是它的内容:

printf("%ws", reposPath.c_str());

此外,您在const的声明中缺少mbstr,应该是这样:

const char* mbstr = "f:\\mypath1\\mypath2\\mypath3";

并且您不需要为char缓冲区分配wchar_t数量的两倍,因此就足够了:

if (c_ReposPathString) { c_ReposPathStringSize = strlen(c_ReposPathString) + 1; // Don't need "* 2" }

随时要求进一步的澄清和/或解释。
© www.soinside.com 2019 - 2024. All rights reserved.