Search code examples
c++chartype-conversionint

Conversion from int to char failed and console prints weird symbol


I am having a weird issue and I don't know how to explain it. When I run this code it prints this symbol -> . This is my code:

#include <iostream>

int main() {
     int num = 1;
     char number = num;

     std::cout<<number<<std::endl;

     system("PAUSE");
     return 0;
}

I don't understand why. Normally it should convert the integer to char. I am using Dev C++ and my language standard is ISO C++11. I am programming for 4 years now and this is the first time I get something like this. I hope I explained my issue and if someone can help me I will be grateful.

enter image description here


Solution

  • Conversion from int to char failed

    Actually, int was successfully converted to char.

    Normally it should convert the integer to char.

    That's what it did. The result of the conversion is char with the value 1.

    Computers use a "character encoding". Each symbol that you see on the screen is encoded as a number. For example (assuming ASCII or compatible encoding) the value of 'a' character is 97.

    A char with value of 1 is not the same as char with the value that encodes the character '1'. As such, when you print a character with value 1, you don't see the number 1, but the character that the value 1 encodes. In the ASCII and compatible encodings, 1 encodes a non-visible symbol "start of heading".


    I wanted to print 1 as a char.

    You can do it like this:

    std::cout << '1' << '\n';