Concat a wchar_t and TCHAR

Concat a wchar_t and TCHAR

本文关键字:and TCHAR wchar Concat      更新时间:2023-10-16

嗨,我需要在我的项目中连接我的对话框的名称(类型wchar_t)和配置的名称(类型TCHAR)。我该怎么做呢?谢谢。

这取决于,TCHAR是char还是wchar_t,这取决于您是否将应用程序构建为Unicode。如果你用Unicode来构建你的应用,你可以简单地这样做:

wcscat_s(dest, extra);

如果你不将你的应用程序构建为Unicode,你需要将TCHAR:s字符串(然后是char:s字符串)转换为wchar_t:s字符串或wchar_t:s字符串转换为char:s字符串。要做到这一点,您应该查看MultiByteToWideChar或widechartommultibyte函数。这两种方法看起来都有点吓人,所以我通常使用一些帮助器(请注意,为了清晰起见,已经删除了正确的错误处理,如果使用ERROR_INSUFFICIENT_BUFFER调用失败,正确的解决方案还将在循环中调用上述函数,以调整缓冲区大小):

std::wstring multiByteToWideChar(const std::string &s)
{
  std::vector<wchar_t> buf(s.length() * 2);
  MultiByteToWideChar(CP_ACP,
                      MB_PRECOMPOSED,
                      s.c_str(),
                      s.length(),
                      &buf[0],
                      buf.size());
  return std::wstring(&buf[0]);
}
std::string wideCharToMultiByte(const std::wstring &s)
{
  std::vector<char> buf(s.length() * 2);
  BOOL usedDefault = FALSE;
  WideCharToMultiByte(CP_ACP,
                      WC_COMPOSITECHECK | WC_DEFAULTCHAR,
                      s.c_str(),
                      s.length(),
                      &buf[0],
                      buf.size(),
                      "?",
                      &usedDefault);
  return std::string(&buf[0]);
}

除此之外,我还设置了一个类型特征类,以便我可以将我的项目编译为Unicode或不关心:

template <class CharT>
struct string_converter_t;
template <>
struct string_converter_t<char>
{
  static std::wstring toUnicode(const std::string &s)
  {
    return multiByteToWideChar(s);
  }
  static std::string toAscii(const std::string &s)
  {
    return s;
  }
  static std::string fromUnicode(const std::wstring &s)
  {
    return wideCharToMultiByte(s);
  }
  static std::string fromAscii(const std::string &s)
  {
    return s;
  }
};

wchar_t的几乎相同的实例(我留下作为练习)。在您的情况下,您可以简单地执行:

std::wstring result = dialog_name + string_converter_t<TCHAR>::toUnicode(config_name);

你是说TCHAR*?因为用一个字符作为名字会有点奇怪。无论如何:只要将TCHAR转换为wchar_t - TCHAR要么是char要么是wchar_t,无论哪种方式都可以将其转换为wchar_t。

http://msdn.microsoft.com/en-us/library/cc842072.aspx

这个问题类似于:不能从'const wchar_t *'_char *'

要手动操作不同类型的字符,请查看:http://www.codeproject.com/KB/TipsnTricks/StringManipulations.aspx