I'm writing a custom numeric class, "BigInt" which I want to integrate with any standard ostream.
While I want this to work
I also want this to work:Code:std::cout << aBigInt << std::endl;
While I want this to work
So far, I am able to do this: (simplified removed lots of else, checks)Code:std::cout << std::hex << aBigInt << std::endl; std::cout << std::dec << aBigInt << std::endl; std::cout << std::oct << aBigInt << std::endl;
This all works pretty nice, but I am having trouble with "std::showbase" and "std::internal". (as in "0x000000a7" instead of "a7")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; }
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:
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.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(); }
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)?


Reply With Quote
Bookmarks