c++type-conversionstdvectorlpcstr

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


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'


Solution

  • 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
        );
    }