如何将int字符串与消息框一起使用?

时间:2012-12-31 20:07:55

标签: c++ winapi casting

我试图通过将int转换为const CHAR *来获取一个消息框来显示变量的地址,我目前的功能失调尝试看起来像这样:

#include <cstdlib>
#include <iostream>
#include <windows.h>

int main()
{
 int *ip;
 int pointervalue = 1337;
 int thatvalue = 1;
 ip = &pointervalue;
 thatvalue = (int)ip;
 std::cout<<thatvalue<<std::endl;
 MessageBox (NULL, (const char*)thatvalue, NULL, NULL);
 return 0;
}

dos框打印2293616,消息框打印“9 |”

4 个答案:

答案 0 :(得分:5)

如果您使用的是C ++ 11,还可以使用to_string()

MessageBox (NULL, std::to_string(thatvalue).c_str(), NULL, NULL);

您当前的问题是,您只是将thatvalue转换为const char*,或者换句话说,取int值并将其转换为指针,而不是字符串(C风格或其他方式)。你的消息框中已经出现了垃圾邮件,因为const char*指针指向无效的垃圾内存,这是一个令人遗憾的奇迹,它没有崩溃。

答案 1 :(得分:3)

尝试使用stringstream(包括sstream)

int *ip;
int pointervalue = 1337;
int thatvalue = 1;
ip = &pointervalue;    
stringstream ss;
ss << hex << ip;
MessageBox (NULL, ss.str().c_str(), NULL, NULL);

答案 2 :(得分:1)

简单的施法不会做这个工作。

查看itoa函数:http://www.cplusplus.com/reference/cstdlib/itoa/

/* itoa example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  int i;
  char buffer [33];
  printf ("Enter a number: ");
  scanf ("%d",&i);
  itoa (i,buffer,10);
  printf ("decimal: %s\n",buffer);
  itoa (i,buffer,16);
  printf ("hexadecimal: %s\n",buffer);
  itoa (i,buffer,2);
  printf ("binary: %s\n",buffer);
  return 0;
}

答案 3 :(得分:1)

转换为const char *不起作用,因为它试图将int解释为指针。

如果你想避开流,你可以像这样使用snprintf

char buffer[20];
snprintf(buffer,20,"%d",thatValue);
MessageBox (NULL, (const char*)buffer, NULL, NULL);