-
June 3rd, 2009, 03:40 AM
#1
ostream base flags with custom numeric class
I'm writing a custom numeric class, "BigInt" which I want to integrate with any standard ostream.
While I want this to work
Code:
std::cout << aBigInt << std::endl;
I also want this to work:
While I want this to work
Code:
std::cout << std::hex << aBigInt << std::endl;
std::cout << std::dec << aBigInt << std::endl;
std::cout << std::oct << aBigInt << std::endl;
So far, I am able to do this: (simplified removed lots of else, checks)
Code:
std::ostream& BigInt::tostream (std::ostream& ioOut)
{
std::ios_base::fmtflags ff(ioOut.flags());
if (ff & std::ios_base::hex) ioOut << getHexString();
if (ff & std::ios_base::dec) ioOut << getDecString();
if (ff & std::ios_base::oct) ioOut << getOctString();
return ioOut;
}
This all works pretty nice, but I am having trouble with "std::showbase" and "std::internal". (as in "0x000000a7" instead of "a7")
Because what I am returning to the stream is actually an std::string, I have to emulate their behavior by hand, by hand-inserting the base, then inserting in between the internal padding, the inserting the string into the stream. I gives me something like this:
Code:
std::ios_base::fmtflags baseFlags(ioOut.flags());
std::stringstream aSsBase;
std::stringstream aSsNumber;
if ( baseFlags & std::ios_base::showbase ) aSsBase << "0x";
aSsNumber << getHexString(); //See above code, compacted here
if ( baseFlags & std::ios_base::internal )
{
aSsBase << std::setfill(ioOut.fill());
aSsBase << std::setw(ioOut.width() - aSsBase.str().size() );
aSsBase << std::right;
}
aSsBase << aSsNumber.str();
ioOut << aSsBase.str();
}
So anyways, that's how I do it. Is there a way to avoid all the above? Not only is it a bit hackish, I'm not even sure all platforms use "0x" and "0" as base prefix, and overall, doesn't look very portable. Finally, there are probably a bunch of flags I am miss-handling/forgetting.
Would it be possible to insert a string into the stream, but somehow tell the stream it should treat it as a number, and let it take care of the rest (padding, base etc)?
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|