c - EOF 位于输入中间

标签 c windows stdin eof

我的问题是关于如何在输入中间解释 EOF,这是一个示例:

int main() {

  int a, b;
    printf("enter something >\n");
    scanf("%d", &a);
    while((b = getchar()) != EOF) {
      printf("%i\n", b);
    }
  return b;
 }

我运行程序并输入:

 1hello^Z(control+z)abc

输出是:

 104 (ascii number for h)
 101 (for e)
 108 (l)
 108 (l) 
 111 (o)
 26 (what is this?)

数字 1 由 scanf 读取,剩余的保留在缓冲区中,getchar() 获取所有这些数字,直到 ^Z,这是预期的行为,因为控件 z 关闭标准输入。 然而26从哪里来呢?如果 getchar() 读取的最后一个值是 EOF,为什么 -1 不是最后一个值?另外,为什么这个程序在读取 ^Z 时没有跳出循环,为什么我需要使用控制 z 再次调用 EOF 来终止循环? 26 是 SUB 的 ascii,我不知道该怎么理解。

谢谢。

最佳答案

当循环结束时,b=26,因为您输入了 ctrl+z,这在返回时被解释为 SUB 。 http://en.wikipedia.org/wiki/Substitute_character

In the ASCII and Unicode character sets, this character(SUB) is encoded by the number 26 (1A hex). Standard keyboards transmit this code when the Ctrl and Z keys are pressed simultaneously (Ctrl+Z, by convention often described as ^Z).

关于c - EOF 位于输入中间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28223254/

相关文章:

c# - windows服务的键盘敲击

c - 保护内存中的凭据

从管道读取的 Golang 读取大量数据

Powershell 无法从标准输入运行多行命令?

C- fprintf 两个变量在同一行

从 setuid root C 程序调用脚本 - 脚本不以 root 身份运行

c - 联网计算机未接收到多播

windows - 如何避免在 Windows 中过度填充 PATH 环境变量?

python - Python 中的 "stderr"有什么意义?

python - 如何使用 malloc 将 char** 返回到 ctypes