将 std::string 转换为 wchar_t* 的类型定义
Converting std::string to a typedef of wchar_t*
我正在通过控制台从用户读取文件目录,我必须将值存储在pxcCHAR*
变量中,这是 SDK 对wchar_t*
typedef
。
我发现我可以通过执行以下操作将std::string
转换为std::wstring
。
#include <iostream>
int main(){
std::string stringPath;
std::getline(std::cin, stringPath);
std::wstring wstrPath = std::wstring(stringPath.begin(), stringPath.end());
const wchar_t* wcharPath = wstrPath.c_str();
return 0;
}
运行此代码时,我通过调试看到这些值。
stringPath= "C:/Users/"
wstrPath= L"C:/Users/"
wcharPath= 0x00b20038 L"C:/Users/"
连接到wcharPath
前面的值从何而来?
此外
因为pxcCHAR*
是wchar_t*
的typedef
,所以我认为简单地这样做是可以的:
pxcCHAR* mFilePath = wcharPath;
但是,我收到一条消息,指出"const wchar_t*"不能用于初始化类型为"pxcCHAR*"的实体。
我期望隐式转换起作用,但事实并非如此。如何克服此错误?
使用std::wstring(stringPath.begin(), stringPath.end())
是处理字符串转换的错误方法,除非您可以保证只处理 7 位 ASCII 数据(文件系统并非如此(。这种类型的转换根本不考虑字符编码。 将std::string
转换为std::wstring
的正确方法是使用std::wstring_convert
、MultiByteToWideChar()
或其他等效项。 如果你环顾四周,有很多这样的例子。
最好一开始就使用std::wstring
而不是std::string
,例如:
#include <iostream>
#include <string>
int main(){
std::wstring stringPath;
std::getline(std::wcin, stringPath);
const wchar_t* wcharPath = stringPath.c_str();
return 0;
}
连接到
wcharPath
前面的值从何而来?
调试器。它只是向您显示指针指向的内存地址,然后是该地址的实际字符数据。
我收到一条消息,指出"const wchar_t*"不能用于初始化类型为"pxcCHAR*"的实体。
这意味着pxcCHAR
不是const wchar_t
的typedef,而更可能是本身wchar_t
的typedef。无论使用何种类型,都不能将const
指针分配给非const
指针。 如果需要进行此类分配,则必须将const
键入,例如使用const_cast
:
pxcCHAR* mFilePath = const_cast<wchar_t*>(wcharPath);
读取转换 Unicode 和 ANSI 字符串。您应该使用MultiByteToWideChar
.
话虽如此,您不太可能需要这样做(并且很可能对于任何非CP1252 的代码页,结果都是不正确的(。您可能必须在任何地方使用宽字符串。
哦,阅读 绝对最低限度 每个软件开发人员绝对,肯定必须了解 Unicode 和字符集(没有借口!
- 有没有一种方法可以通过"typedef"为重新定义的基本类型定义特征和强制转换运算符
- 强枚举类型定义:Clang Bug 还是 C++11 标准不确定性?
- 列表参数的类型定义
- 使用模板化的键类型定义 std::map,该键类型基于作为参数接收的函数
- 关于 C++ 中的函数类型定义
- C++(和 ROS) - 包含与前向声明引用,设置默认值和类型定义
- 将使用/类型定义限制为类范围
- 模板类型定义?
- C++:模板类的类型定义
- 如何对命名空间限定类型进行类型定义?
- 此递归模板类型定义是否有效C++?
- 具有调整对齐方式的类型定义
- C++从抽象类型定义类成员
- 用于C++代码的 API 监视器类型定义 (XML)
- 如何将result_of与函数类型定义一起使用
- 在C++的适当类型定义位置
- 如何根据模板类型定义浮点常量?
- 如何为缺少预定义运算符而不扩展命名空间"std"的标准类型定义运算符>> (istream &, ...)?
- 参数化类的别名(或类型定义)内部类
- 如果我想从类型"T"定义元素的容器(来自 STL),那么"T"必须使用默认构造函数?