0

以下代码有效:

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

为了自动清理,我使用了以下信息:如何将 std::string 转换为 const char* 或 char*?.

以下代码引发错误:

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

我收到此错误: “MessageBoxA”:无法将参数 2 从“std::vector<_Ty>”转换为“LPCSTR”

4

3 回答 3

4

你不能将向量作为 LPCSTR 传递,你必须。采用:

&writable[0]

或者:

writable.data()

反而。或者干脆使用myString.c_str()

于 2017-02-02T17:09:55.410 回答
2

MessageBox需要一个const char*. 为此,您无需先复制字符串。只需使用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
    );
}

请注意,我认为您的 API 很差:您正在修改传入的字符串的值。通常调用者不会期望这样。我认为你的函数应该是这样的:

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
    );
}
于 2017-02-02T17:21:18.777 回答
0
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
    );
}

谢谢大家和@Falcon

于 2017-02-02T17:22:36.747 回答