getchar() 函数如何输出
How getchar() function output
我想了解getchar()
函数在这里是如何工作的?
我读取getchar()
返回stdin
的下一个字符,或者如果到达文件末尾,则返回EOF
。
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
int decimal;
while(!isdigit(decimal=getchar()));
cout<<decimal;
}
我给出输入 25。它输出 50。我不明白为什么?它如何给50。
>getchar()
从输入流中读取单个字符并返回其值。在您的情况下,这就是角色'2'
。大多数实现(包括你的实现(都使用 ASCII 编码,其中字符'2'
的值50
.因此,分配给decimal
的值50
。由于decimal
是一个int
,std::cout
将其解释为一个数值并相应地打印出来。
decimal
正在存储它找到的第一个数字字符,恰好是'2'
。您将值存储到int
,因此cout
输出序号值 decimal
。'2'
的 ASCII 序数值为 50
。你甚至从未到达你输入的5
。
使其显示字符而不是序号值的简单修复方法是将输出代码更改为:
cout << (char)decimal;
当您输入25
时,它会从此输入中读取第一个字符。这里2
第一个字符。2
的 ASCII 值为 50
。这就是为什么你在输出时得到50
。
如果您想在输出中使用这样的2
cout << (char) decimal << endl;
在这里,类型转换50
为字符。那是2
.
C 库函数 int getchar(void( 从 stdin(一个无符号字符(获取一个字符。
此外,十进制是整数类型,isdigit(十进制(将检查ASCII小数位的字符。
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
int decimal;
while(!isdigit(decimal=getchar()));\when you input 25. It first gets 2.
\ 2 gets stored as 50 inside decimal
\ isdigit() is called which returns true for 50 which is ASCII of 2 and while breaks
cout<<decimal; \ 50 is printed here. Type cast it to print 2.
}
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 为什么我的代码在输出中增加了93天
- 如何从void函数输出字符串
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- AES加密到解密未正确输出
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 如何将地图<列表<string>、矢量<string>>输出到输出文件?
- 为什么立即输出立即输出
- 该代码将如何工作以及输出的输出是什么
- 以未格式化的输出 c++ 打印输出
- 程序未正确输出到输出文件
- 程序从不输出任何输出
- 代码将无意义输出到输出文件而不是字符串
- NetBeans IDE:"Run Success"输出在输出完成之前发生
- [输入],[输出],[输入,输出]和[输出,重新评估]之间有什么区别?