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

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?

本文关键字:整数 一个 分配 为什么 输入 在其中 我们 字符 如果 输出      更新时间:2023-10-16
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"吗?它被分配了一个整数的值?

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

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

  1. int变量的大小为 4(或 8(个字节,具体取决于您的计算机,而char变量仅为 1 个字节。
  2. 由于类型升级char可隐式转换为int
  3. 数字具有其 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 个字符,而 char bar 最多只能容纳 1 个字符,因此,输出将为 6。

相关文章: