我尝试使用以下 C 程序从标准输入读取整数。
#include <unistd.h>
#include <stdio.h>
int main() {
int a = 0;
read(0, &a, sizeof(int));
printf ("a = %d\n",a);
}
但是,我得到了奇怪的结果:当我输入 34 时,我认为程序输出 34,但它却输出 668723。为什么?
最佳答案
如Weather Vane张贴在comments :
read()
读取字节而不是ascii
The read() function shall attempt to read bytes from the file
ASCII 34\n
变为二进制的 0001010 00110100 00110011
。 (或者实际上是 \n43
由于字节顺序)
接下来0001010 00110100 00110011
转换成十进制就变成668723
关于c - 从 stdin 读取整数会产生奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49988033/