Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is std::cout not printing the correct value for my int8_t number?

Tags:

c++

gdb

cout

I have something like:

int8_t value;
value = -27;

std::cout << value << std::endl;

When I run my program I get a wrong random value of <E5> outputted to the screen, but when I run the program in gdb and use p value it prints out -27, which is the correct value. Does anyone have any ideas?

like image 289
Grammin Avatar asked Sep 28 '11 18:09

Grammin


People also ask

Why is cout not printing anything?

This may happen because std::cout is writing to output buffer which is waiting to be flushed. If no flushing occurs nothing will print. So you may have to flush the buffer manually by doing the following: std::cout.


2 Answers

Because int8_t is the same as signed char, and char is not treated as a number by the stream. Cast into e.g. int16_t

std::cout << static_cast<int16_t>(value) << std::endl;

and you'll get the correct result.

like image 124
Cat Plus Plus Avatar answered Sep 28 '22 05:09

Cat Plus Plus


This is because int8_t is synonymous to signed char.

So the value will be shown as a char value.

To force int display you could use

std::cout << (int) 'a' << std::endl;

This will work, as long as you don't require special formatting, e.g.

std::cout << std::hex << (int) 'a' << std::endl;

In that case you'll get artifacts from the widened size, especially if the char value is negative (you'd get FFFFFFFF or FFFF1 for (int)(int8_t)-1 instead of FF)

Edit see also this very readable writeup that goes into more detail and offers more strategies to 'deal' with this: http://blog.mezeske.com/?p=170


1 depending on architecture and compiler

like image 21
sehe Avatar answered Sep 28 '22 04:09

sehe