Re: Stroustrup 4.11 exercise 4
* arnuld:
On Mar 26, 8:39 pm, "Mike Wahler" <mkwah...@mkwahler.net> wrote:
<ios> declares stream manipulators, except those
taking arguments, which are declared by <iomanip>.
i tried this:
------------ PROGRAMME -----------
#include<iostream>
#include<cctype>
#include<ios>
int main()
{
std::cout << "CHAR \tDECIMAL\tHEX" << std::endl;
for(int i=0; i <= 127; ++i)
{
char ic = char(i);
if(isprint(ic))
{
std::cout << "'"
<< ic
<< "' : \t"
<< i
<< '\t'
<< std::ios::hex
<< i
<< std::endl;
}
}
return 0;
}
--------- OUTPUT ----------
[arch@voodo tc++pl]$ g++ -ansi -pedantic -Wall -Wextra 4.11_4.cpp
[arch@voodo tc++pl]$ ./a.out
CHAR DECIMAL HEX
' ' : 32 832
'!' : 33 833
'"' : 34 834
---------------------
i only USED some part of OUTPUT of here to make post shorter. you can
see the 1st line: DECIMAL "32" equals "832" in HEX. but it does not,
see:
HEX 832 = 8*16^2 + 3*16^1 + 2*16^0
= 2048 + 48 + 2
= 2098 IN DECIMAL
what is wrong with my programme ?
A number of things.
First, unrelated to the hex, the conversion of 'i' to 'ic', to serve as
argument to 'isprint', does exactly the Wrong Thing. For the range you
have chosen, 0 through 127, it doesn't matter. But if increased that
range to say 0 through 255, then the conversion would introduce a
possible bug whereas all would be OK if you just used 'i' directly.
Second, regarding the hex. It's evident from the output that
std::ios::hex is display as '8', then 'i' is displayed in decimal. And
the reason is that the program is using the wrong 'hex', again because
it does to much: simply write 'std::hex', not 'std::ios::hex'.
Third, still regarding the hex. It sets the stream to a persistent
"display as hex" mode. Thus, when the code has been fixed as explained
above, only the first line of output will show any decimal number, the
rest will all be in hex.
I leave it to you to figure out a solution to that. ;-)
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?