954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

cout types

With printf, you specify the output type like this

unsigned char a;
printf("%u", a);

but with cout,

cout << a;

there is no type required. Do you have to cast the variable in order to see a reasonable output

cout << (int)a;

or something like that? How do you know which type to convert to? Ie when I do cout << a; I get some crazy ascii character, but what I wanted to see was a value between 0 and 255.

Thanks!

Dave

daviddoria
Posting Virtuoso
1,996 posts since Feb 2008
Reputation Points: 437
Solved Threads: 204
 

Because you did not initialize it..Example..

// declare n init
unsigned char a='a';
// display
std::cout<<a;
cikara21
Posting Whiz
340 posts since Jul 2008
Reputation Points: 47
Solved Threads: 69
 

no, it is initialized (i guess I should have written that). I get the value from a function, ie.

unsigned char a[3];
glReadPixels(a); // puts data into a

cout << a;

It outputs a crazy character - I would like to see the value (0-255).

Dave

daviddoria
Posting Virtuoso
1,996 posts since Feb 2008
Reputation Points: 437
Solved Threads: 204
 
std::cout<<static_cast<int>(a[0]); // n next
cikara21
Posting Whiz
340 posts since Jul 2008
Reputation Points: 47
Solved Threads: 69
 
cikara21
Posting Whiz
340 posts since Jul 2008
Reputation Points: 47
Solved Threads: 69
 

a is not a char, is an array of char. you have to print its component one at a time.

mrboolf
Junior Poster
183 posts since Jun 2008
Reputation Points: 134
Solved Threads: 18
 

bah I mis-typed again, I was trying to do

cout << a[0];

not

cout << a;

With the correct version, I do infact have to cast it as an int.

what is the difference between
cout<(a[0]);

and

cout << (int)a[0];

?

Thanks

Dave

daviddoria
Posting Virtuoso
1,996 posts since Feb 2008
Reputation Points: 437
Solved Threads: 204
 

The difference between (int) and static_cast is really the limitation
of static_cast<>

I think it is easier to see an example and then discuss it.
E.g.

char A('x');
double X[50];

int i=static_cast<int>(A);      // OK
int k=(int) A;
long int j = (int) X;
long int k = static_cast<long int>(X);   // FAILS AT COMPILE
long int z=reinterpret_cast<long int>(X); // OK


Basically, static_cast will only allow conversions between related types.
Note, the very subtle error in the code above (int) X will work BUT loses precision so the full address is not converted [ok I know it is machine dependent.. but 64 bit/gcc is does], and that alone is worth the extra typing.

StuXYZ
Practically a Master Poster
680 posts since Nov 2008
Reputation Points: 760
Solved Threads: 138
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You