如何将 int 转换为 LPCTSTR?赢32.

How do I convert a int to LPCTSTR? Win32

本文关键字:LPCTSTR 转换 int      更新时间:2023-10-16

我想在win32 MessageBox中显示一个int值。我已经阅读了一些不同的方法来执行此转换。有人可以为我提供一个好的实现。

Win32 编程的新手,因此:)轻松

更新

这就是我目前所拥有的。它有效..但文本看起来像中文或其他一些双字节字符。我不是在摸索 Unicode 与非 Unicode 类型。有人可以帮助我了解我哪里出错了吗?

 int volumeLevel = 6;
 std::stringstream os;
 os<<volumeLevel;
 std::string intString = os.str();  
  MessageBox(plugin.hwndParent,(LPCTSTR)intString.c_str(), L"", MB_OK);

像 belov 一样转换为 MFC :

int number = 1;
CString t;
t.Format(_T("%d"), number);
AfxMessageBox(t);

用过,它对我有用。

LPCTSTR的定义如下:

#ifdef  UNICODE
typedef const wchar_t* LPCTSTR;
#else
typedef const char* LPCTSTR;
#endif

std::string::c_str()仅返回const char*。您无法将const char*直接转换为 const wchar_t* 。通常编译器会抱怨它,但是对于LPCTSTR转换,您最终会迫使编译器对此闭嘴。因此,它当然不会像您在运行时预期的那样工作。为了建立你的问题,你可能想要的是这样的东西:

// See Felix Dombek's comment under OP's question.
#ifdef UNICODE
typedef std::wostringstream tstringstream;
#else
typedef std::ostringstream tstringstream;
#endif
int volumeLevel = 6;    
tstringstream stros;    
stros << volumeLevel;     
::MessageBox(plugin.hwndParent, stros.str().c_str(), L"", MB_OK);  

n几种方法:

int value = 42;
TCHAR buf[32];
_itot(value, buf, 10);

另一种对您的情况更友好的方式:

int value = 42;
const size_t buflen = 100;
TCHAR buf[buflen];
_sntprintf(buf, buflen - 1, _T("the value is %d"), value);
int OurVariable;
LPCWSTR result=(to_string(OurVariable).c_str());

LPCWSTR result=LPCSTR(to_string(OurVariable).c_str());

LPCSTR result=(to_string(OurVariable).c_str());

它真的有效

对 Unicode 感知代码使用_T()装饰器:

int number = 1;
CString t;
t.Format(_T("%d"), number);
AfxMessageBox(t);

参考: https://social.msdn.microsoft.com/Forums/vstudio/en-US/f202b3df-5849-4d59-b0d9-a4fa69046223/how-to-convert-int-to-lpctstr?forum=vclanguage