Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Char variable value not being displayed

Excuse the vague title ( I didn't know how to address the issue). Anyways, within my code I explicitly declared a few variables, two being signed/unsigned int variables, and the others being signed/unsigned char type variables.

My code:

#include <iostream>

int main(void) 
{
    unsigned int number = UINT_MAX;
    signed int number2 = INT_MAX;
    unsigned char U = UCHAR_MAX;
    signed char S = CHAR_MAX;

    std::cout << number << std::endl;
    std::cout << "The size in bytes of this variable is: " << sizeof(number) <<       std::endl << std::endl;

    std::cout << number2 << std::endl;
    std::cout << "The size in bytes of this variable is: " <<sizeof(number2) << std::endl << std::endl;

    std::cout << U << std::endl;
    std::cout << "The size in bytes of this variable is: " << sizeof(U) << std::endl
        << std::endl;

    std::cout << S << std::endl;
    std::cout << "The size in bytes of this variable is: " <<sizeof(S) << std::endl << std::endl;

    std::cin.get();
    std::cin.get();

    return 0;
}

Sorry the code is scrambled due to excessive length, but my issue is that my char variables are not "printing" to my output. It outputs their size in bytes, but no matter what I do I can't seem to get it to work. Also, The second char variable (signed (S)) prints what appears to look like a triangle, but nothing else.

like image 638
Jake2k13 Avatar asked Mar 28 '26 10:03

Jake2k13


1 Answers

Try this:

std::cout << (int)U << std::endl;
std::cout << "The size in bytes of this variable is: " << sizeof(U) << std::endl
    << std::endl;

std::cout << (int)S << std::endl;
std::cout << "The size in bytes of this variable is: " <<sizeof(S) << std::endl << std::endl;

The explanation is so simple: when the type is char, cout is trying to produce a symbolic output which is whitespace for 255 or a pretty-like triangle for 127. When the type is int, cout just prints the value of the variable. For example in C:

printf("%d", 127) // prints 127
printf("%c", 127) // prints triangle, because %c formatter means symbolic output
like image 180
Netherwire Avatar answered Mar 30 '26 00:03

Netherwire



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!