如果我们向它输入一个整数,那么一个字符会给出整数作为输出,但是当一个整数被分配给它时,这不会发生。为什么?

A character gives integer as output if we input an integer into it but this doesn't happen when an integer is assigned to it. Why?

int p=89; //An integer defined and declared
    char g;   //A character defined
    g=p;      //Assigning the character the value of the integer p
    cout<<g;  //Here the output comes out to be "Y"
    cout<<endl<<"Enter any number";
    cin>>g;
    cout<<g;  //Here the output is coming out to be the integer you have inputted

它不应该输出一个整数而不是给出"Y"吗?正在为其分配整数值?

当您将一个整数分配给字符变量时,它会从内存中读取整数并存储在它的位置,并且在解释该 char 值时,它 returns 等效于它的 ASCII。在将 cin 缓冲区读入字符变量 (char) 时,它会读取 char 的 1 个字节或其内存中的 ASCII 值,并将输出作为等效的 ASCII 值给出。

您需要了解 intchar 之间的区别。

  1. int 变量的大小为 4(或 8)字节,具体取决于您的机器,而 char 变量仅为 1 字节。
  2. 由于 类型提升 .
  3. char 可隐式转换为 int
  4. 数字有其对应的 ASCII 字符。

所以,

int p=89; //An integer defined and declared
char g;   //A character defined
g=p;      //Assigning the character the value of the integer p, which is 'Y' in ASCII - note single quotes
cout<<g;  //Here the output comes out to be 'Y'
cout<<endl<<"Enter any number";
cin>>g; // say 88, but since size of char is 1 byte, it only saves the first character, i.e., '8'
cout<<g; // prints '8' the character, not the integer

当您向 char g 输入内容时,您实际上输入的是 char 而不是 ASCII 值。

例如:

    char bar;
    cin>>bar;// assume you type 67
    cout<<bar;

输出将是 6,因为 67 不是整数而是 2 个字符,而字符栏最多只能容纳 1 个字符,因此输出将是 6。