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
}
但我想将变量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();
相关文章:
- 指向指向字符数组的指针数组的指针
- 比较字符数组
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 使用无符号字符数组有效存储内存
- 按字符值访问int数组
- 错误:字符数组的初始值设定项太多
- 对字符数组中的元素执行逐位操作
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 移动二维数组中的字符
- C++ 传递二维字符数组
- 无法在 C++ 中输入字符数组
- C++ 带结构的数组字符
- 数组字符包含量超出预期
- 读取文件并添加到数组字符
- 如何在Qt中更改或替换数组字符
- 为什么编译器不在参数中传递数组字符 *arr[] 的大小?
- 井字棋数组字符错误
- 分割数组字符