"<< hex" vs cout.setf(ios_base::hex)
What exactly is the difference between the hex manipulator and the
following statement: cout.setf(ios_base::hex)?
According to Stroustrup, Third Edition, Section 21.4.4, "once set, a
base is used until reset". For some reason, I interpreted this to
mean that "<< hex" manipulator would cause the base to be set for only the current statement, while the cout.setf(ios_base::hex) statement would cause the base to be set for multiple statements, up to the point where it is reset. The following snippet of code, which dumps an arbitrary data structure, seems to behave EXACTLY THE OPPOSITE WAY. Thanks, Gus ///////////////////////////////////////
#include <"iostream">
#include <"sys/types.h">
using namespace std;
#define DS_DUMP_LEN 10
struct point
{
int x;
int y;
};
struct rect
{
point p1;
point p2;
};
void
dumpMemory(void* ds, size_t size)
{
// Uncomment the next line for the desired behavior
// (i.e. restricting the hexadecimal base just to this function)
// ios_base::fmtflags oldFmtSettings = cout.setf(ios::showbase);
char *dsPtr = (char *)ds;
for(size_t i = 0; i < size; i++)
{
if(!(i%DS_DUMP_LEN))
cout << endl;
unsigned char ch = *(dsPtr+i);
cout << hex << int(ch) << " ";
}
cout << endl;
// Uncomment the next line for the desired behavior
// (i.e. restricting the hexadecimal base just to this function)
//cout.setf(oldFmtSettings);
}
////////////////////////////////////////////////////////////
// The intent is to have a hex base only in the dumpMemory()
// routine, and a decimal base everywhere else.
////////////////////////////////////////////////////////////
main()
{
int temp = 16;
rect myRect = {{3, 5}, {14, 47}};
// The following line seems to have no "lingering" effect
// The output that follows still has a decimal base
cout.setf(ios_base::hex);
cout << "Value @ location 1 is " << temp << endl;
dumpMemory(&myRect, sizeof(rect));
// We used the hex manipulator only in the dumpMemory function,
// but it seems to have left behind a lingering effect, and
// the output that follows continues to have a hexadecimal base
cout << "Value @ location 2 is " << temp << endl;
- Generic Usenet Account
1 Comments:
cout.setf( ios_base::hex, ios_base::dec );
Post a Comment
<< Home