从 argv[1] 转换为字符 * 字符串后有什么问题?
What is the issue in following conversion from argv[1] to char * string?
我对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"
}
请随时要求进一步澄清和/或解释。
相关文章:
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- 当我尝试添加 2 个大字符串时,我无法弄清楚出了什么问题
- 初始化或分配空字符串文字到指向 C 中的 char 的指针或指向 C++ 中 const char 的指针的原因是什么
- 在C++17中,引用const字符串的语义应该是什么
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 字符串上的 C++ push_back() 和 pop_back() 的 Kotlin 是什么?
- 我的逻辑反转字符串中的元音有什么问题?
- 我还可以添加什么来按空格或空格正确拆分C++字符串?
- 这里的字符串函数是什么意思
- 我正在尝试使用 while 循环从字符串中删除字母,直到没有字母。我在这里做错了什么?
- 字符串::格式有什么用. 我也没有在互联网上得到它
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 如果结构中的字符串比使用的 p/调用签名长或短,会发生什么情况?
- 这两个C++语句连接字符串有什么区别?
- "in-situ without memory allocation" 字符串的愚蠢实现意味着什么?
- 我做错了什么?反向字符串 C++
- 将位字符串转储到二进制文件的最佳方法是什么
- 使用 CStringW/CStringA 和 CT2W/CT2A 转换字符串有什么区别?
- 使用 const char* 初始化 const ref 字符串成员时幕后会发生什么
- 仅威胁唯一字符串 - 什么是更快的 vector<std::string> 或只是 std::string