如何在 Win32 C++ 中将类型 "int" 转换为类型 "LPCSTR"

How to convert type "int" to type "LPCSTR" in Win32 C++

本文关键字:类型 int LPCSTR 转换 Win32 C++      更新时间:2023-10-16

朋友们好,我如何将类型"int"转换为类型"LPCSTR"?我想将变量"int cxClient"赋予"MessageBox"函数的第二个参数"LPCSTR lpText"。以下是示例代码:

int cxClient;    
cxClient = LOWORD (lParam);    
MessageBox(hwnd, cxClient, "Testing", MB_OK);

但它不起作用。以下函数是"MessageBox"函数的方法签名:

MessageBox(HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType);

使用正确的sprintf变体将int转换为字符串

TCHAR buf[100];
_stprintf(buf, _T("%d"), cxClient);
MessageBox(hwnd, buf, "Testing", MB_OK);

您需要<tchar.h>

我认为_stprintf是这里的快速答案,但如果你想像David建议的那样使用纯C++,那么

#ifdef _UNICODE
wostringstream oss;
#else
ostringstream oss;
#endif
oss<<cxClient;
MessageBox(0, oss.str().c_str(), "Testing", MB_OK);

你需要

#include <sstream>
using namespace std;
using std::to_string
std::string message = std::to_string(cxClient)

http://en.cppreference.com/w/cpp/string/basic_string/to_string