繁体   English   中英

C ++ MessageBox字符数组

[英]C++ MessageBox character array

我在将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
}

但是我想将变量文件名和长度输出为:

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*转换为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项目时,带有此代码的char数组将显示在MessageBox中。 包括头文件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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM