关于scanf和fflush

在C语言的书籍中经常看到scanf()的一下写法:spa

  
  
  
  
  
scanf("%d",&hoge);

scanf不是以行单位对输入内容进行解释,而是对连续的字符流进行解释(包含换行)。scanf()连续地从流中读入字符,而且对和格式说明(%d)想匹配的的部分进行变换处理。指针

例如,格式说明符为%d时,输入code

123↵get

此时,从流中取得123,可是↵依然残留在输入流中,可能会被后面的过程吞掉,形成不想要的结果。input

例如:
it

  
  
  
  
  
#include <stdio.h>int main(void){int hoge;char buf[256];printf("&hoge...%p\n",&hoge);printf("Input intitial value.\n");// fgets(buf,sizeof(buf),stdin);// sscanf(buf,"%d",&hoge);scanf("%d",&hoge); //若是使用scanf则后面的getchar()会吞掉结束的回车符fflush(stdin);for(;;){printf("hoge..%d",hoge);getchar();hoge++;}return 0;}

这里第一个getchar()将会吞掉↵。io

此外scanf()在读入的过程当中,成功转换为几个字符就返回几。function

例如class

  
  
  
  
  
while (scanf("%d", &hoge) != 1) {printf("输入错误,请再次输入!");}

上面的例子也不能用fflush(stdin)来处理虽然能获得同样的结果,可是在其余的平台上却会获得不肯定的结果。由于fflush()是对输出流使用的而不是对输入流使用的。C++标准中是这样描述的:stream


int fflush(FILE *stream);

If stream points to an output stream or an update stream in which
the most recent operation was not input, the fflush function causes
any unwritten data for that stream to be delivered to the host environment
to be written to the file; otherwise, the behavior is undefined.


参考文献:

《征服C指针》

C++ referrence:http://www.cplusplus.com/reference/cstdio/fflush/

 

相关文章
相关标签/搜索