getchar() 函数如何输出

How getchar() function output

本文关键字:输出 何输出 函数 getchar      更新时间:2023-10-16

我想了解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是一个intstd::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. 
}