c - 为什么标准输入流中没有出现多个 `\n` 字符?

标签 c newline stdin scanf

这个问题一直困扰着我。考虑以下程序:

#include <stdlib.h>
#include <stdio.h>

int main(void){

  char one,mid,final;
  int num;

  printf("Enter the first character:\n");
  scanf("%c",&one);

  printf("Enter any integer:\n");
  scanf("%d",&num);

  printf("Enter the middle character:\n");
  scanf("%c",&mid);

  printf("Enter the final character:\n");
  scanf("%c",&final);

  printf("You have entered\n");
  printf("\"%c\" and \"%d\" and \"%c\" and \"%c\"\n",one,num,mid,final);

  return EXIT_SUCCESS;
}

假设输入是

A\n
34\n
B\n

这里,

第一个 scanf 获取 A 并将 \n 保留在 stdin 中。
第二个nd不使用\n,因为%d跳过它们,因此得到34。这个scanf 还将 \n 字符保留在 stdin 中。
第三个rd scanf 获取第二个scanf 留下的\n
第 4 个th scanf 获取 B 并再次将 \n 保留在 stdin 中>.

我的问题是:为什么最后一个 scanf 不消耗第一个 scanf 留下的 \n 字符?

最佳答案

跳过的字符不在流中“左侧”。输入流只能在一个方向上读取一次,1,因此一旦跳过一个字符,它就会消失。

1 没有额外的花哨,例如缓冲

关于c - 为什么标准输入流中没有出现多个 `\n` 字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27924996/

相关文章:

c - C 中从命令行输入的字符串或字符

c - 基于 C 中另一个字符数组的奇怪长度和内容

在多行中捕获的正则表达式适用于 regex101.com 但不适用于 PowerShell

node.js - 如何使用 Node.js 和 Express 进行\r\n 回车/换行

C stdin 无限读取文件

c - 为什么我应该在 CTRL+D 之前按 ENTER 以向标准输入指示 EOF?

go - 相当于 Go 中的 freopen

c++ - Clang 中 -g 和 -gfull 的区别

C 中内存读写的自定义处理

linux - 如何在 Linux 终端中删除 CRLF 字符(回车换行符)?