Pergunta

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.

Foi útil?

Solução

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

Outras dicas

They are printed but you cannot see it. You can open the file of "limits.h":

#define CHAR_BIT      8         /* number of bits in a char */
#define SCHAR_MIN   (-128)      /* minimum signed char value */
#define SCHAR_MAX     127       /* maximum signed char value */
#define UCHAR_MAX     0xff      /* maximum unsigned char value */

then you look for UCHAR_MAX and CHAR_MAX in the ASCII table,

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top