c++ - 如何将 long 转换为 LPCWSTR?

标签 c++ string type-conversion

如何在 C++ 中将 long 转换为 LPCWSTR?我需要类似于此的功能:

LPCWSTR ToString(long num) {
    wchar_t snum;
    swprintf_s( &snum, 8, L"%l", num);
    std::wstring wnum = snum;
    return wnum.c_str();
}

最佳答案

您的函数被命名为“to string”,转换为字符串确实比转换“to LPCWSTR”更容易(也更通用):

template< typename OStreamable >
std::wstring to_string(const OStreamable& obj)
{
  std::wostringstream woss;
  woss << obj;
  if(!woss) throw "dammit!";
  return woss.str();
}

如果您有需要 LPCWSTR 的 API,则可以使用 std::wstring::c_str():

void c_api_func(LPCWSTR);

void f(long l)
{
  const std::wstring& str = to_string(l);
  c_api_func(str.c_str());
  // or 
  c_api_func(to_string(l).c_str());
}

关于c++ - 如何将 long 转换为 LPCWSTR?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1572705/

相关文章:

c++ - BOOST_AUTO_TEST_SUITE_END() 行出现异常错误

php - 使用php获取字符串中第一个大写字母的位置

c++ - 确定最佳转换的 Variadic 模板

go - 如何在 Go 中将 [Size]byte 转换为字符串?

c++ - 如何避免在非构造函数上进行隐式转换?

c++ - 两个函数变量到一个函数

c++ - 加权随机数

php - 字符串加密/解密

python - 从反斜杠到斜杠(创建以数字命名的文件夹)

c++ - 将 LPBYTE 转换为字符串