INTtoCHAR函数couts错误的值

时间:2015-05-30 12:41:58

标签: c++

这是我的功能:

signed char INTtoCHAR(int INT)
{
    signed char CHAR = (signed char)INT;
    return CHAR;
}

int CHARtoINT(signed char CHAR)
{
    int INT = (int)CHAR;
    return INT;
}

它正确地将int值赋给char,但是当我想cout那个char然后它给了我一些我们的标志。它编译没有错误。

我的测试代码是:

int main()
{
  int x = 5;
  signed char after;
  char compare = '5';
  after = INTtoCHAR(5);

  if(after == 5)
  {
      std::cout << "after:" << after << "/ compare: " << compare << std::endl;
  }


  return 0;
}

之后确实是5但它不打印5.任何想法?

2 个答案:

答案 0 :(得分:2)

使用一元运算符+添加上述答案,还有另一种方法:typecasting

std::cout << "after:" << (int)after << "/ compare: " << compare << std::endl;

Correct output

答案 1 :(得分:1)

打印时使用 terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::at ,而不是+after。这会将after提升为可打印的类型,无论其类型如何。

所以改变这个:

after

到此:

std::cout << "after:" << after << ", compare: " << compare << std::endl;

有关详情,请参阅此answer