为什么不能在MessageBox上显示这个字符串? [英] Why can't I display this string on MessageBox?

查看:851
本文介绍了为什么不能在MessageBox上显示这个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个指向一些字符的指针,但是在赋给它一些值之后,然后试图在MessageBox上打印它,编译它给我一些错误。我的代码如下:

  #include< Windows.h> 
#include< string.h>
#include< iostream>
using namespace std;

void main()
{

char buff [100];
string id =ST_5;
sprintf_s(buff,id:%s,id.c_str());


MessageBox(NULL,buff,LUser-id,MB_OK);

}

请帮助我在这个代码中找到问题,谢谢。



我的编译器输出:
c:\users\zafri\documents\visual studio 2012\projects\test3\test3\ test3.cpp(19):error C2664:'MessageBoxW':无法将参数2从'char [100]'转换为'LPCWSTR'
指向的类型是不相关的;转换需要reinterpret_cast,C风格的转换或函数式转换

解决方案

您应该阅读编译器错误消息。

MessageBox 的第二个和第三个参数必须具有相同的类型。您可以使用两个 char * 调用 MessageBoxA ,或者调用 MessageBoxW 两个 wchar_t *



您的代码的一个修复将是 MessageBoxA(NULL,buff,User-id,MB_OK)



您也使用了 sprintf_s 错误,请阅读其文档。 IMHO最好使用标准函数 snprintf

  snprintf (buff,sizeof buff,%s,id.c_str());请注意,您可以删除 buff  


$ b <完全写入:

  MessageBoxA(NULL,id.c_str(),User-id,MB_OK); 


I've created a pointer pointing to a couple of chars but after assigning it to some value and then trying to print it on the MessageBox and compiling it is giving me some errors.My code is given below:

 #include <Windows.h>
 #include <string.h>
 #include <iostream>
 using namespace std;

 void main()
 {

  char buff[100];
  string id = "ST_5";
  sprintf_s(buff, "id: %s", id.c_str());


   MessageBox(NULL, buff,L"User-id", MB_OK);

 }

Please help me in finding the problem in this code, Thanks.

My compiler's output: c:\users\zafri\documents\visual studio 2012\projects\test3\test3\test3.cpp(19): error C2664: 'MessageBoxW' : cannot convert parameter 2 from 'char [100]' to 'LPCWSTR' Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast

解决方案

You should read the compiler error messages.

The second and third arguments to MessageBox have to have the same type. Either you call MessageBoxA with two char *, or you call MessageBoxW with two wchar_t *.

One fix for your code would be to do MessageBoxA(NULL, buff, "User-id", MB_OK).

You are using sprintf_s incorrectly too, please read its documentation. IMHO it would be better to use the standard function snprintf:

snprintf(buff, sizeof buff, "%s", id.c_str());

Note that you could do away with buff entirely and write:

MessageBoxA(NULL, id.c_str(), "User-id", MB_OK);

这篇关于为什么不能在MessageBox上显示这个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆