【问题标题】:Converting std::string to a typedef of wchar_t*将 std::string 转换为 wchar_t* 的 typedef
【发布时间】:2017-07-26 17:19:29
【问题描述】:

我正在通过控制台从用户处读取文件目录,我必须将值存储在pxcCHAR* 变量中,即SDK 的typedef 用于wchar_t*

我发现我可以通过执行以下操作将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*typedefwchar_t*,所以我认为只需这样做就可以了:

pxcCHAR* mFilePath = wcharPath;

但是,我收到一条消息说“const wchar_t*”不能用于初始化“pxcCHAR*”类型的实体。

我希望隐式转换能够工作,但事实并非如此。我该如何克服这个错误?

【问题讨论】:

标签: c++ typedef wchar-t


【解决方案1】:

使用std::wstring(stringPath.begin(), stringPath.end()) 是处理字符串转换的错误方法,除非您可以保证您只处理 7 位 ASCII 数据(文件系统不是这种情况)。这种类型的转换根本不考虑字符编码。将std::string 转换为std::wstring 的正确方法是使用std::wstring_convertMultiByteToWideChar() 或其他等效项。如果您环顾四周,就会有很多这样的例子。

最好只使用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);

【讨论】:

    【解决方案2】:

    阅读Converting Unicode and ANSI Strings。你应该使用MultiByteToWideChar

    话虽如此,您不太可能需要这样做(并且很可能任何代码页的结果都不正确notCP1252)。您可能需要在任何地方使用宽字符串。

    哦,阅读The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

    【讨论】:

      猜你喜欢
      • 2011-05-19
      • 2010-09-19
      • 2016-01-28
      • 1970-01-01
      相关资源
      最近更新 更多