2012-12-31 19 views
1

我試圖得到一個消息通過鑄造一個int到一個const char *顯示變量的地址,我目前不正常的嘗試看起來是這樣的:如何在消息箱中使用int字符串?

#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,在MessageBox打印「9 |」

回答

1

鑄造到const char *不起作用,因爲它然後嘗試將int解釋爲指針。

如果你想避免流可以使用的snprintf像這樣

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

嘗試使用字符串流,而不是(包括sstream)

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

出於好奇,爲什麼'hex'? – Cornstalks

+0

由於指針通常以十六進制格式查看。 –

+0

@RyanGuthrie:啊,我錯過了那個問題中的thatvalue是指針的值。說得通。 – Cornstalks

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; 
} 
+0

只是來自該網站關於可能會影響某些人的'itoa'的一個重要注意事項:「此函數未在ANSI-C中定義,並且不是C++的一部分,但由某些編譯器支持。 – Cornstalks

5

如果您使用C++ 11,你也可以使用to_string()

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

您當前的問題是,你」只是鑄造thatvalueconst char*,換句話說,取int值並將其轉換爲指針,而不是字符串(C型或其他)。你的消息框中印有垃圾信息,因爲const char*指針指向的是無效的垃圾內存,這是一個不幸的奇蹟,它不會崩潰。

相關問題