getchar()函数如何输出

How getchar() function output

我想了解 getchar() 函数在这里是如何工作的?

我读取 getchar() returns 来自 stdin 的下一个字符,或者 EOF 如果到达文件末尾。

#include <iostream>
#include <cstdio>
using namespace std;

int main() {
    int decimal;
    while(!isdigit(decimal=getchar()));
    cout<<decimal;
}

我输入25,输出50,不明白为什么? 怎么给50.

decimal 正在存储它找到的第一个数字字符,恰好是 '2'。您将值存储到 int,因此 cout 输出 decimal 的序数值。 '2' 的 ASCII 序数值是 50。您甚至没有达到输入的 5

使其显示字符而不是序数值的简单修复方法是将输出代码更改为:

cout << (char)decimal;

getchar() reads a single character from the input stream and returns it's value. In your case, that is the character '2'. Most implementations (including yours it seems) use ASCII encoding 其中字符 '2' 的值为 50。因此分配给 decimal 的值是 50。由于 decimal 是一个 intstd::cout 将其解释为数值并相应地打印它。

当您输入 25 时,它会从此输入中读取第一个字符。这里的第一个字符是 22 的 ASCII 值是 50。这就是你在输出中得到 50 的原因。

如果你想在输出中看到 2 像这样使用

cout << (char) decimal << endl;

这里type-casting转成50字符。即2.

C 库函数 int getchar(void) 从标准输入获取一个字符(无符号字符)。

另外,decimal是整数类型,isdigit(decimal)会检查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. 
}