【问题标题】:How to convert type "int" to type "LPCSTR" in Win32 C++如何在 Win32 C++ 中将类型“int”转换为类型“LPCSTR”
【发布时间】:2013-07-12 10:18:58
【问题描述】:

你好朋友,我如何将类型“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);

【问题讨论】:

    标签: c++ winapi messagebox


    【解决方案1】:

    使用正确的 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;
    

    【讨论】:

    • 由于问题被标记为 C++,也许 C++ 的答案会更好
    • @DavidHeffernan - 也用 ostringstream 添加一个。
    • 哇!我得到了它。现在“MessageBox”函数可以显示我想要的变量 :D 。以下是我的工作代码:#include using namespace std; #ifdef _UNICODE wostringstream oss; #else ostringstream oss; #endif oss
    • @Bhaddiya 除了条件代码,您还可以使用typedef std::basic_ostringstream&lt;TCHAR&gt; tostringstream。或者将 wostringstream 与 UNICODE 变体 MessageBoxW 一起使用。
    【解决方案2】:
    using std::to_string
    
    std::string message = std::to_string(cxClient)
    

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

    【讨论】:

    • 注意std::to_string需要C++11
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-12
    • 2014-02-20
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    • 1970-01-01
    • 2021-06-07
    相关资源
    最近更新 更多