Nurav
Nurav

Reputation: 177

Concatenating LPCSTR variable and literal?

I have a LPCSTR variable name and I want to use it in MessageBoxA(NULL,name,"pop up",MB_OK); where I want name to hold value name+" is X". For example name has value John so I am expecting output on Message Box as "John is X". Can anyone help me with this?

I tried using std::(string(name)+string(" is X")).c_str(); since I am using MessageBoxA and need to concatenate LPCSTR.

I know how to use it for MessageBoxW which takes argument LPCWSTR. I have used this way before.

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

Upvotes: 0

Views: 528

Answers (3)

Remy Lebeau
Remy Lebeau

Reputation: 595367

The simpliest options is to convert the LPCSTR to a std::string, then you can append to it as needed, eg:

#include <string>

LPCSTR name = ...;

MessageBoxA(NULL, (std::string(name) + " is X").c_str(), "pop up", MB_OK);

Another option is to use a std::ostringstream, eg:

#include <string>
#include <sstream>

LPCSTR name = ...;

std::ostringstream oss;
oss << name << " is X";
MessageBoxA(NULL, oss.str().c_str(), "pop up", MB_OK);

Upvotes: 2

MSalters
MSalters

Reputation: 179779

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

That's a bit weird. std:: is a namespace qualification, and it only applies to the name directly following it. You can't say std::(X,Y,Z) and have that std:: apply to all of X,Y and Z.

The idea itself is good. (std::string(name) + std::string(" is X")).c_str() will work as intended.

Upvotes: 0

Ted Lyngmo
Ted Lyngmo

Reputation: 117168

You can create a string from the LPCSTR and then add " is X" to it.

Here's an example putting the result as both caption and text in the MessageBoxA:

#include <string>

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

Upvotes: 3

Related Questions