【问题标题】:How do I concatenate a string and wstring?如何连接字符串和 wstring?
【发布时间】: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


【解决方案1】:

首先将wstring 转换为string,例如this

std::string result = std::string(wStr.begin(), wStr.end()) + str;

或者如果wStr包含非ASCII字符:

std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
std::string wStrAsStr = converter.to_bytes(wStr);
std::string result = wStrAsStr + str;

【讨论】:

  • 这种转换在一般情况下会丢失信息,并且根据使用的约定,它可能会产生无效的std::string 值(例如,UTF-8 编码的无效字节),因此推荐它而不提及限制有点鲁莽。
  • 添加了更安全的选择。
  • :) 现在它不会丢失信息,这很好,但由于这是 Windows 编程,它不再很有用:不能作为路径工作,并且不能在 GUI 中正确显示东西(我相信可以将流配置为在控制台中正确显示它,但不确定)。但是,它可以用作例如宽字符串的序列化。这完全取决于 OP 忽略提及的目的
猜你喜欢
  • 1970-01-01
  • 2023-03-08
  • 2012-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-12
  • 2015-07-21
相关资源
最近更新 更多