C++MessageBox字符数组

C++ MessageBox character array

本文关键字:数组 字符 C++MessageBox      更新时间:2023-10-16

我在使用带有变量的MessageBox函数时遇到困难

我有

int main(int argc, char* argv[])
{
   char* filename = argv[0];
   DWORD length = strlen(filename);
   MessageBox(0, TEXT("filename text"), TEXT("length text"), 0); // Works
}

但我想将变量filename和长度输出为:

MessageBox(0, filename, length, 0); -- compiler error

函数MessageBox具有语法:

int WINAPI MessageBox(
  _In_opt_  HWND hWnd,
  _In_opt_  LPCTSTR lpText,
  _In_opt_  LPCTSTR lpCaption,
  _In_      UINT uType
);

我试过使用

MessageBox(0, (LPCWSTR)filename, (LPCWSTR)length, 0);

但是输出的是某种象形文字。

变量length不是字符串,只能使用字符串。尝试将其强制转换为char*并没有帮助,因为length的值将被用作指向字符串的指针,这将导致未定义的行为。

对于C++,您可以使用例如std::to_string将非字符串值转换为字符串,如

MessageBox(0, filename, std::to_string(length).c_str(), 0);

请注意,必须使用c_str函数才能获得char*

如果您没有std::to_string,则可以使用例如std::istringstream

std::istringstream is;
is << length;
MessageBox(0, filename, is.str().c_str(), 0);

如果您想要一个更老式的C解决方案,那么有snprintf(或Visual Studio中的_snprintf):

char length_string[20];
_snprintf(length_string, sizeof(length_string), "%ld", length);
MessageBox(0, filename, length_string, 0);

对于VS2015中的C++win32项目,在MessageBox中显示一个包含以下代码的char数组。包括标头atlstr.h

// open a file in read mode.
ifstream myInfile;
myInfile.open("C:\Users\Desktop\CodeOnDesktop\myTrialMessageBox.txt");
if (myInfile.fail())
{
    MessageBox(NULL,
        L"We have an error trying to open the file myTrialMessageBox.txt",
        L"Opening a file.",
        MB_ICONERROR);
}
char data[200];
// Read the data from the file and display it.
//infile >> data;   // Only gets the first word.
myInfile.getline(data, 100);
//To use CString, include the atlstr.h header.
// Cast array called data to a CString to enable use as MessageBox parameter.
CString cdata = (CString)data;
// or CString cdata = CString(_T("A string"));
MessageBox(NULL,
    cdata,
    L"Opening a file.",
    MB_ICONERROR);
// close the opened file.
myInfile.close();