Decimal string to Pointer via StringStream

Started by
3 comments, last by rip-off 11 years, 8 months ago
C++ iostreams provide a method to output (void *) pointers. The pointer is written to and read from a stream in hexadecimal notation.

How can I use decimal notation without resorting to a reinterpret_cast and ugly #ifdefs?

I tried this:

std::stringstream ss;

void *test = (void *)0x12345678;

// Output pointer as decimal number
ss << std::ios::dec << test; // Works!

// Read pointer from decimal number
void *x;
ss << dec; // Nope
ss.setf(std::ios::dec); // No change
ss >> dec >> x; // Neither


All the input variants do nothing. The pointer will not be assigned and keeps its "help I'm uninitialized" value of 0xcccccccc. The fail bit of the stream is set - probably because it tried to _still_ parse the number in hex and it was too large.
Professional C++ and .NET developer trying to break into indie game development.
Follow my progress: http://blog.nuclex-games.com/ or Twitter - Topics: Ogre3D, Blender, game architecture tips & code snippets.
Advertisement
It might not answer your question, but why do you want to (a) write the pointer out in decimal, and (2) why on Mars would you want to read in a pointer?

Stephen M. Webb
Professional Free Software Developer

Why are you trying to read a pointer from a stream? That seems incredibly dangerous.

Interestingly, the following code appears to compile on my system:

#include <iostream>


int main() {
void *foo;
if(std::cin >> foo) {
std::cout << "Read a pointer?\n";
} else {
std::cout << "Failed\n";
}
}

However explicitly trying to call the operator fails:

#include <iostream>


int main() {
void *foo;
if(operator>>(std::cin, foo)) {
std::cout << "Read a pointer?\n";
} else {
std::cout << "Failed\n";
}
}

[s]I suspect the former program is actually calling a built in operator >> after some type converting, for example converting the two sides to booleans or something.[/s] (See Alvaro's response, I am wrong).
Calling `operator>>(std::cin, foo)' explicitly doesn't work if foo is an int either.

Reading a pointer from a stream is a valid operation, but there is no guarantee that the accepted format is decimal. In g++ the format seems to be hexadecimal. I can't bother to look it up in the standard, but my guess is that the only guarantee is that it will understand whatever format `<< foo' spits out.

Calling `operator>>(std::cin, foo)' explicitly doesn't work if foo is an int either.
[/quote]
Interesting, Needless to say, I don't explicitly call operators like that often. I was hoping an explicit call would allow me to "jump to declaration" in my IDE.


Reading a pointer from a stream is a valid operation...
[/quote]
Also interesting. Yet another entry in the C++ minefield to watch out for.

This topic is closed to new replies.

Advertisement