[RESOLVED] setbase not setting the base for cout
I'm having trouble understanding why this code doesn't work. I am copying almost verbatim from msdn help for the setw iomanip library function. It should set the base for output, but it isn't.
Code:
#include <iostream>
#include <iomanip>
using namespace std;
int paws;
int base = 10;
const double d1 = 16.0;
const double d2 = 256.0;
const double d3 = 1024.0;
const double d4 = 4096.0;
const double d5 = 65536.0;
void printBases(double input)
{
cout << "input: " << input << ", oct:" << setbase(8) << input << ", hex:" << setbase(16) << input << "\n";
}
void DisplayLongs( )
{
cout << setbase(10);
cout << endl << "setbase(" << base << ")" << endl;
cout << setbase(base);
cout << "l1 = " << d1 << endl;
cout << "l2 = " << d2 << endl;
cout << "l3 = " << d3 << endl;
cout << "l4 = " << d4 << endl;
cout << "l5 = " << d5 << endl;
}
int main()
{
printBases(d1);
printBases(d2);
printBases(d3);
printBases(d4);
printBases(d5);
base = 16;
DisplayLongs();
base = 8;
DisplayLongs();
base = 10;
DisplayLongs();
return (EXIT_SUCCESS);
}
output:
C:\My Programs\pretest3\Debug>pretest3
input: 16, oct:16, hex:16
input: 256, oct:256, hex:256
input: 1024, oct:1024, hex:1024
input: 4096, oct:4096, hex:4096
input: 65536, oct:65536, hex:65536
setbase(16)
l1 = 16
l2 = 256
l3 = 1024
l4 = 4096
l5 = 65536
setbase(8)
l1 = 16
l2 = 256
l3 = 1024
l4 = 4096
l5 = 65536
setbase(10)
l1 = 16
l2 = 256
l3 = 1024
l4 = 4096
l5 = 65536
C:\My Programs\pretest3\Debug>
:confused::confused::confused:
Re: setbase not setting the base for cout
Quote:
Originally Posted by
MattInSD73
I'm having trouble understanding why this code doesn't work. I am copying almost verbatim from msdn help for the setw iomanip library function. It should set the base for output, but it isn't.
Change those doubles to longs. What are your results?
Similarly, what if you changed one of the double values to 16.5 instead of 16.0? What would you have expected your output to be?
Regards,
Paul McKenzie
Re: setbase not setting the base for cout
I assumed that the doubles would get converted to the proper base, but apparently cout and setbase don't play that well enough together as to accept a non-integral type. Luckily, I don't need the fractional values, so I can truncate with a cast to long.
Thanks for the help! :wave:
Code:
void printBases(double input)
{
cout << setbase(10) << "input: " << (long) input << ", oct:" << setbase(8) << (long) input << ", hex:" << setbase(16) << (long) input << "\n";
}