Char变量值未显示

Jak*_*k13 3 c++ outputstream char

请原谅模糊的标题(我不知道如何解决这个问题).无论如何,在我的代码中我明确地声明了一些变量,两个是有符号/无符号的int变量,其他是有符号/无符号的char类型变量.

我的代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

抱歉代码因长度过长而被扰乱,但我的问题是我的char变量没有"打印"到我的输出.它输出它们的大小(以字节为单位),但无论我做什么,我似乎无法让它工作.此外,第二个char变量(signed(S))打印看起来像三角形的内容,但没有别的.

Net*_*ire 6

试试这个:

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;
Run Code Online (Sandbox Code Playgroud)

解释是如此简单:当类型是char,cout正在尝试产生whitespace255 的符号输出或127的非常类似的三角形.当类型是时int,cout只打印变量的值.例如在C中:

printf("%d", 127) // prints 127
printf("%c", 127) // prints triangle, because %c formatter means symbolic output
Run Code Online (Sandbox Code Playgroud)

  • 很好的修改,以这种方式进行转换会更好:static_cast <int>(VAR)还是(int)? (2认同)