【问题标题】:Char variable value not being displayed字符变量值未显示
【发布时间】:2014-01-07 17:33:47
【问题描述】:

请原谅模糊的标题(我不知道如何解决这个问题)。无论如何,在我的代码中,我明确声明了一些变量,两个是有符号/无符号 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;
}

抱歉,由于长度过长,代码被打乱了,但我的问题是我的 char 变量没有“打印”到我的输出中。它以字节为单位输出它们的大小,但无论我做什么,我似乎都无法让它工作。此外,第二个 char 变量 (signed (S)) 打印看起来像三角形的东西,但没有别的。

【问题讨论】:

  • 将它们转换为 int 以显示值而不是 ascii 字符。

标签: c++ char outputstream


【解决方案1】:

试试这个:

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;

解释很简单:当类型为char 时,cout 试图产生一个符号输出,即whitespace 表示 255 或漂亮的三角形表示 127。当类型为 int , cout 只是打印变量的值。例如在 C 中:

printf("%d", 127) // prints 127
printf("%c", 127) // prints triangle, because %c formatter means symbolic output

【讨论】:

  • 这个答案不能比它已经得到的进一步改进。干得好!
  • 大改版,这样转换会更好:static_cast(VAR),还是(int)?
  • 在你的情况下他们是the same
【解决方案2】:

它们是打印出来的,但你看不到。 您可以打开“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 */

然后你在 ASCII 表中查找 UCHAR_MAX 和 CHAR_MAX,

【讨论】:

    猜你喜欢
    • 2016-04-03
    • 2020-09-04
    • 1970-01-01
    • 2016-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    相关资源
    最近更新 更多