Jack Harvin
Jack Harvin

Reputation: 6765

Format String C++

I have a pointer and I would like to convert the pointer address to a string and display the address in a message box. Is there a function similar to printf() that can format a string? This does not seem to work.

#include <windows.h>
#include <stdio.h>

int WINAPI WinMain(
    HINSTANCE hThisInstance,
    HINSTANCE prevInstance,
    LPSTR lpszArgument,
    int nFunsterStil)
{
  int x = 5;
  int* ptr = &x; 

  MessageBox(NULL, printf("%p", ptr), "Pointer", MB_OK);
  return 0;    
}

Thanks for any help.

Upvotes: 1

Views: 1178

Answers (4)

Andreas Brinck
Andreas Brinck

Reputation: 52549

Either use sprintf (or as someone else suggested, the more safe snprintf) to first print the pointer to a buffer or even better use a stringstream to put the pointer in a string.

stringstream tmp;
tmp << ptr;
MessageBox(NULL, tmp.str().c_str(), "Pointer", MB_OK);

Upvotes: 4

MSalters
MSalters

Reputation: 180265

Looks like a conversion that Boost can do: MessageBox(NULL, boost::lexical_cast<std::string>(&x).c_str(), "Pointer", MB_OK);

Upvotes: 1

Moo-Juice
Moo-Juice

Reputation: 38820

Check out std::ostringstream:

#include <sstream>

std::ostringstream oss;
int a(5);
std::string b("Hello!");

oss << "This is an example! " << a << ", so I will say " << b;

// use oss.str() to return a string!

Upvotes: 1

Eir Nym
Eir Nym

Reputation: 1599

sprintf is good, but snprintf is better

Upvotes: 0

Related Questions