how to convert integer into string pointer in visual c++?
If you want a textual representation of the pointer address use sprintf. If you want to treat the numeric value as a pointer to a string use casting like so:
int intValue = ...; char * charPtr = (char*)intValue;
You got homework? a generic one, tested if g++, http://effocore.googlecode.com/svn/trunk/devel/effo/codebase/addons/inl/include/impl/algo_impl.h :
#ifdef __cplusplus
static inline char *int2a_put(uintptr_t i, char *s)
{
do {
*s++ = '0' + i % 10;
i /= 10;
} while (i);
return s;
}
static inline void int2a_reverse(char *head, char *tail)
{
for (*tail = '\0'; --tail > head; ++head) {
/* exchange */
(*head) ^= (*tail);
(*tail) ^= (*head);
(*head) ^= (*tail);
}
}
template<typename t>
static inline const char *int2a(t i, char *s)
{
char *p;
char *ret = s;
bool f = false;
p = s;
if (i < 0) {
*p++ = '-';
++ s;
/*
* In limits.h, INT_MAX was defined as
* maximum values a `signed int' can hold.
* and LONG_MAX was defined as maximum values
* a `signed long int' can hold.
*/
switch (sizeof(t)) {
case 8:
{
/*
* Inject \p a to prevent from complaint
* of compiler.
*/
ef64_t a = (ef64_t)i;
if (-LLONG_MAX > a) {
i = (t)LLONG_MAX;
f = true;
}
}
break;
case 4:
case 2:
case 1:
{
/*
* Inject \p a to prevent from complaint
* of compiler.
*/
int a = (int)i;
if (-INT_MAX > a) {
i = (t)INT_MAX;
f = true;
}
}
break;
default:
break;
}
if (!f) {
i = -i;
}
}
p = int2a_put((uintptr_t)i, p);
if (f) {
++ *s;
}
int2a_reverse(s, p);
return ret;
}
/*
* No "static" otherwise g++ complains
* "explicit template specialization cannot have a storage class"
*/
template<>
/*static*/ inline
const char *int2a<uintptr_t>(uintptr_t i, char *s)
{
char *p = int2a_put(i, s);
int2a_reverse(s, p);
return s;
}
#else
If you using CString, then you can use Format() method like this:
int val = 489;
CString s;
s.Format("%d", val);
search for atoi / itoa in your favorite documentation. Or try Boost (www.boost.org - library Conversion, lexical_cast).
Both ways are portable across different compilers.
Take any C and C++ textbook. This simple C code should work in Visual C++ and others C++ compilels and convert 489 into "489":
char result[100];
int num = 489;
sprintf(result, "%d", num);
Use stringstream
#include <sstream>
stringstream ss;
ss << i;
string s = ss.str();
This is how I did it in my homework since we were only allowed to use some predetermined libraries. I'm pretty sure it's not considered a "best practice" though ;)
string int2string(int integer) {
string str;
int division = integer;
while (division > 0) {
str = char('0' + (division % 10)) + str;
division = division / 10;
}
return str;
}