c++ - 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.
解决方案
您不能简单地将字符串重新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";
而且您不需要char
为wchar_t
缓冲区分配两倍的数量,所以这就足够了:
if (c_ReposPathString)
{
c_ReposPathStringSize = strlen(c_ReposPathString) + 1; // Don't need "* 2"
}
随时要求进一步澄清和/或解释。
推荐阅读
- node.js - 如何在 Node js 中构建电子邮件功能?
- php - 调用未定义的方法 App\UserShiftPattern::userWorkScheduleList()
- python - 数据框条形图与 plt.plot 的 x 轴不一致
- javascript - 403 响应代码 - 使用 Cowin setu API 时请求被阻止
- beautifulsoup - 为什么 VScode ChromeDriver 不显示我试图打开的网站 url?
- kubernetes - 无法使用自定义插件运行 Traefik:“命令 traefik 错误:无法检查插件 XXX 的存档完整性:插件完整性检查失败”
- html - 为什么
标签或任何其他标签没有相互堆叠?
- button - 使用绑定隐藏非选定 cellView 中的按钮
- arduino - Arduino led 矩阵 max7219 MCU 板点阵
- c# - .editorconfig 用于测试项目/类