'MessageBoxA' : cannot convert parameter 2 from 'std::vector<_Ty>' to 'LPCSTR'

753 views Asked by At

The following code works:

void CMyPlugin8::myMessageBox(std::string& myString)
{
    myString = "Received the following string\n" + myString;
    char * writable = new char[myString.size() + 1];
    std::copy(myString.begin(), myString.end(), writable);
    writable[myString.size()] = '\0'; // don't forget the terminating 0 "delete[] writable;"

    int msgboxID = MessageBox(
        NULL,
        writable,
        "Notice",
        MB_OK
    );
    delete[] writable;
}

To clean up automatically I used info from : How to convert a std::string to const char* or char*?.

The following code throws an error:

void CMyPlugin8::myMessageBox(std::string& myString)
{
    myString = "Received the following string\n" + myString;
    std::vector<char> writable(myString.begin(), myString.end());
    writable.push_back('\0');

    int msgboxID = MessageBox(
        NULL,
        writable,
        "Notice",
        MB_OK
    );
}

I'm getting this error: 'MessageBoxA' : cannot convert parameter 2 from 'std::vector<_Ty>' to 'LPCSTR'

4

There are 4 answers

3
Dark Falcon On BEST ANSWER

MessageBox takes a const char*. You don't need to copy the string first for that. Simply use c_str:

void CMyPlugin8::myMessageBox(std::string& myString)
{
    myString = "Received the following string\n" + myString;
    int msgboxID = MessageBox(
        NULL,
        myString.c_str(),
        "Notice",
        MB_OK
    );
}

Note that I think your API is poor: you are modifying the value of the string passed in. Usually the caller wouldn't be expecting that. I think your function should look like this instead:

void CMyPlugin8::myMessageBox(const std::string& myString)
{
    std::string message = "Received the following string\n" + myString;
    int msgboxID = MessageBox(
        NULL,
        message.c_str(),
        "Notice",
        MB_OK
    );
}
0
marcinj On

You cannot pass a vector as LPCSTR, you must. Use:

&writable[0]

or:

writable.data()

instead. Or simply use myString.c_str()

1
Mickey D On
void CMyPlugin8::myMessageBox(const std::string& myString)
{
    std::string message = "Received the following string\n" + myString;
    int msgboxID = MessageBox(
        NULL,
        message.c_str(),
        "Notice",
        MB_OK
    );
}

Thanks everyone & @Falcon

0
Ranjeet R Patil On

If you still face a problem, after changing it myString.c_str(). Try this, Go to the Properties for your Project and under Configuration Properties/Advanced, change the Character Set to "Not Set". This way, the compiler will not assume that you want Unicode characters, which are selected by default:

enter image description here