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

What is the issue in following conversion from argv[1] to char * string?

本文关键字:字符串 什么 问题 字符 argv 转换      更新时间:2023-10-16

我对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]有多个字符它。

您不能简单地将wchar_t字符串重新转换为char字符串并期望它正常工作,因为可能(将(有许多wchar_t值的上字节为零(在强制转换后将被视为终止符(。

因此,而不是:

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

f后看到一个"假"的 nul-terminator,只需打印wchar_t字符串即可:

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

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

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

而且,您无需为wchar_t缓冲区分配两倍的char数,因此这就足够了:

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

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