C ++ MessageBox字符数组

时间:2013-09-05 09:58:58

标签: c++ winapi types messagebox

我在使用带变量的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和length输出为:

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

但输出是某种象形文字。

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:-1)

使用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();