C buffer

这学期在Dartmouth上ENGS20(Introduction to Scientific Computing),好多东西不记下来就会忘,所以开一个笔记。

在C语言中,输入和输出都是有buffer的,即使在程序中写了“printf”,也不会马上在屏幕上输出,而是存在buffer这样一个存储区域,只有在两种情况下buffer中的东西才会被显示出来,第一是buffer已经被填满了,第二种就是你故意把它搞出来。第二种又分两个情况,'scanf'和'\n'。而用‘fprintf’向文件中输入,如果buffer满了,也会输出,或者你可以用“fflush”手动输出。

其实,C语言为输入(键盘)和输出(显示器)创造了两种特殊文件,“stdin”和“stdout”,这些文件我们可以把它当做其他已经被打开的文件来使用,以下两个语句是等效的:

fprintf(stdout, "%c", ch);

printf("%c", ch);

需要注意的是,在debug的时候一定要用printf(“\n”); 而不是printf(“”); 因为即使程序出现错误后者无法显示你的debugging信息。


#include<stdio.h>

int main(void){
  int a, b;
  printf("Enter a number:");
  scanf("%d", &a);
  printf("Enter another number: ");
  scanf("%d", &b);
  printf("You have entered %d and %d\n", a, b);
  return (0);
}

/*
sample output:

Enter a number:3
Enter another number: 45
You have entered 3 and 45

Enter a number:3 45
Enter another number: You have entered 3 and 45
*/

在上面的这个程序中,如果连续输入两个数,第二个scanf在input buffer中发现了45,于是程序直接结束。


   char a, b;
   printf("enter a character:");
   scanf("%c", &a);
   printf("enter another character:");
   scanf("%c", &b);
   printf("haha, you got an error!\n");

/*
sample output:
enter a character:r
enter another character:haha, you got an error!
*/

在上面这个例子中,你在第一个字母之后的按下的“enter”键对“scanf” function来说也是有效的输入,所以第二个“scanf”就把enter读到“b”中,这都是和input buffer有关的非常有趣的bug。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值