【发布时间】:2016-03-10 19:54:38
【问题描述】:
我在 C++ 中有一个 wstring 变量和一个字符串变量。我想将它们连接起来,但简单地将它们加在一起会产生构建错误。我怎样才能将它们结合起来?如果我需要将 wstring 变量转换为字符串,我该如何完成呢?
//A WCHAR array is created by obtaining the directory of a folder - This is part of my C++ project
WCHAR path[MAX_PATH + 1] = { 0 };
GetModuleFileNameW(NULL, path, MAX_PATH);
PathCchRemoveFileSpec(path, MAX_PATH);
//The resulting array is converted to a wstring
std::wstring wStr(path);
//An ordinary string is created
std::string str = "Test";
//The variables are put into this equation for concatenation - It produces a build error
std::string result = wStr + str;
【问题讨论】:
-
遵循 Windows 约定,
std::string通常不能表示宽字符串。如果它打算用作文件系统路径,那么这是一个特定的转换,但如果它是要显示给用户的,那么这是一个不同的转换。所以这在很大程度上取决于您打算使用std::string的目的,它的用途是什么? -
“普通字符串”是一个奇怪的术语。您希望结果是哪种字符集和编码?如果不是 Unicode 编码(例如 UTF-8),您将丢失数据,因为
GetModuleFileNameW将是 UTF-16 代码单元的计数序列。
标签: c++ string concatenation wstring