如果我们在其中输入一个整数,则字符会给出整数作为输出,但是当分配给它一个整数时,这不会发生。为什么?
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"
吗?它被分配了一个整数的值?
当您为字符变量分配整数时,它会从内存中读取该整数并存储在其位置,在解释该字符值时,它会返回它的 ASCII 等效值。在将 cin 缓冲区读取到字符变量 (char( 时,它会读取内存中的 char 或其 ASCII 值的 1 个字节,并将输出作为 ASCII 等效项给出
。您需要了解int
和char
之间的区别。
int
变量的大小为 4(或 8(个字节,具体取决于您的计算机,而char
变量仅为 1 个字节。- 由于类型升级,
char
可隐式转换为int
。 - 数字具有其 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。
相关文章:
- C++需要帮助从用户那里获得一个整数,并确保它在另外两个整数之间
- 当我们从/tp地址中添加/减去一个整数时会发生什么
- 如何将一个数组值合并为一个整数c++
- 为什么有时我输入一个整数,程序将第一个输入的数字打印成十进制数?
- 给定一个整数数组,需要在Max_Heap上运行操作。得到错误"segmentation fault",有什么想法吗?(C++)
- 我可以将迭代器递增一个整数吗?
- 有没有办法生成一个包含平方的序列,这些平方加起来就是一个整数平方?
- 我正在尝试制作一个程序,在添加 n 天(整数)后告诉一个人什么是一天(例如星期一等)
- 为什么将两个浮点数相加会得到一个整数C++?
- 编写一个读取五个整数并执行一些任务的C++程序
- 如果我们在其中输入一个整数,则字符会给出整数作为输出,但是当分配给它一个整数时,这不会发生。为什么?
- 给枚举一个整数,并在 C++ 中将其相关值作为字符串获取
- 我需要编写一个程序来读取一个文件,该文件将输出所有唯一的整数,如果已经看到整数,它将被关闭
- 按升序输出整数时,将最后一个整数放在新行上
- 编写一个程序,提示用户输入一个整数,然后输出数字的单个数字和数字的总和
- 我在c++中遇到了一个奇怪的错误,其中一个计算2个小整数加法的语句溢出到一个长值中
- 如何在C++中将一个值拆分为一个十进制整数
- 给定一个整数 N>0,区间 [0, 2^N) 中有多少个整数正好有 N-1 个设置位?编写一个返回正确答案的简短函数
- 我必须更改我的数字最后一个数字和第一个数字,但不要使用仅带有整数或循环的函数.例如从 12345 到 52341
- 将整数范围映射到另一个范围