A simple C ++ type conversion program

I learn C ++ and do safe and unsafe conversions. Here is my code:

#include <iostream>

using namespace std;
int main()
{
    double d = 0;
    while( cin >> d )
    {
           int i = d; // try to squeez in a double into an int
           char c = i; // try to squeez in an int into a char
           int i2 = c; // try to get the integer value of the char

           cout << "d == " << d << "\n"
                << "i == " << i << "\n"
                << "c == " << c << "\n"
                << "i2 == " << i2 << "\n";
    }
    return 0;
}

when I enter 3, I get the following:

d == 3
i == 3
c == a heart shape
i2 == 3

why cprints out the listening form as follows: link

+4
source share
5 answers

Because the heart symbol is a symbol with a value of 3 in the PC version of the ASCII table. Here is the list: http://www.ascii-codes.com/ . You can find other useful codes there, suggesting that your program runs in this environment.

+1
source

char , ostream ( cout) . .

, "" , int(c) c.

, : int(c) - , (int)c, ( ). ( int) , . int char. -, , C-, ++, , ++, .

+1

3, c, . ascii Ctrl-C ETX (0x03), . - . . , , .

+1

'd', double, , . ( i2).

char is sent to the screen without conversion, i.e. sent like that. char 3, if you look in the ASCII table, it actually doesn’t represent anything - the printable characters start with 32. So, you get a "strange" character.

0
source

You see the rendering of a non-printable character represented by a char value of "3".

In your code, the variable c has the value 3. This is actually the "print control character" in the ASCII set. (The symbol "3" is ASCII 33).

He has a representation of a heart symbol when he tries to be printed.

0
source

All Articles