0

here is what my function looks like:

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

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

It works properly that it assigns the int value to the char, but when I want to cout that char then it gives me some weired signs. It compiles without errors.

My testing code is:

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;
}

After is indeed 5 but it doesn't print 5. Any ideas?

Yíu
  • 383
  • 3
  • 14

2 Answers2

2

Adding to the above answer using the unary operator +, there is another way as well: typecasting.

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

Correct output

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Ayushi Jha
  • 4,003
  • 3
  • 26
  • 43
1

Use +after while printing, instead of after. This will promote after to a type printable as a number, regardless of type.

So change this:

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

to this:

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

For more, see this answer.

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305