【问题标题】:Reading an integer from stdin gives strange results从标准输入读取整数会产生奇怪的结果
【发布时间】:2018-04-24 03:38:21
【问题描述】:

我尝试使用以下 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。为什么?

【问题讨论】:

  • 668723 是 0xA34330x0A3433 是 ASCII 换行符,43 反向,由于字节序。
  • scanf("%d", &amp;a);?
  • 不要将 ascii 与二进制混合
  • 你能链接到read() 上的文档吗?
  • read 读取字节,它不会将 ascii 转换为整数

标签: c


【解决方案1】:

正如Weather Vane 发布在comments

read() 读取 bytes 而不是 ascii

read() 函数应尝试从文件中读取字节

ASCII 34\n 变成二进制的0001010 00110100 00110011。 (或者真的是\n43,由于字节序)

接下来0001010 00110100 00110011转换成十进制就变成668723

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-02
    • 2014-03-24
    • 2015-10-04
    • 2019-07-26
    • 2018-10-29
    • 2019-04-07
    • 2011-07-12
    • 1970-01-01
    相关资源
    最近更新 更多