连接 LPCSTR 变量和文字?

Concatenating LPCSTR variable and literal?

本文关键字:文字 变量 LPCSTR 连接      更新时间:2023-10-16

我有一个LPCSTR变量name我想在MessageBoxA(NULL,name,"pop up",MB_OK);中使用它 我希望名称保存值name+" is X".例如,名称具有值John因此我希望消息框上的输出为"John is X". 谁能帮我解决这个问题?

我尝试使用std::(string(name)+string(" is X")).c_str();因为我正在使用MessageBoxA并且需要连接LPCSTR.

我知道如何将其用于需要LPCWSTR论证MessageBoxW. 我以前用过这种方式。

wchar_t waCoord[20];
wsprintf(waCoord, _T("(%i,%i)"),x , y);
MessageBox(hWnd, waCoord, _T(" click"), MB_OK);

您可以从LPCSTR创建string,然后向其添加" is X"

下面是一个将结果作为标题和文本放在MessageBoxA中的示例:

#include <string>
void makebox(LPCSTR name) {
std::string res(name);
res += " is X";
::MessageBoxA(nullptr, res.c_str(), res.c_str(), MB_OK);
}

最简单的选择是将LPCSTR转换为std::string,然后您可以根据需要附加到它,例如:

#include <string>
LPCSTR name = ...;
MessageBoxA(NULL, (std::string(name) + " is X").c_str(), "pop up", MB_OK);

另一种选择是使用std::ostringstream,例如:

#include <string>
#include <sstream>
LPCSTR name = ...;
std::ostringstream oss;
oss << name << " is X";
MessageBoxA(NULL, oss.str().c_str(), "pop up", MB_OK);

std::(string(name)+string(" is X"))

这有点奇怪。std::是命名空间限定,它仅适用于紧随其后的名称。你不能说std::(X,Y,Z),就让std::适用于所有X,Y和Z。

这个想法本身是好的。(std::string(name) + std::string(" is X")).c_str()将按预期工作。