首页 > 解决方案 > What is the issue in following conversion from argv[1] to char * string?

问题描述

I am very new to C and pointers. I am trying to convert command line argument to wchar_t * . But somehow it is not giving proper output. What am I missing?

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);
}

when I print length of w_path, it shows 1. But argv[1] has more than one character it it.

标签: c++argvwchar-twidestring

解决方案


您不能简单地将字符串重新wchar_t转换为char字符串并期望它起作用,因为可能(将)许多 wchar_t值的高字节为零(在转换之后将被视为终止符)。

所以,而不是:

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

在 之后看到一个“假”的 nul 终止符f,只需打印wchar_t字符串的内容:

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

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

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

而且您不需要charwchar_t缓冲区分配两倍的数量,所以这就足够了:

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

随时要求进一步澄清和/或解释。


推荐阅读